Can anyone tell me how to create a linked-list in swift with node as structure and linked-list as class.
I tried to create a node Node with reference to itself and faced a error "value type 'Node' cannot have a stored property that references itself"
for resolving it i created one more class Next
and now I am unable to proceed further.
You can not make node as a "struct" since Swift treats Struct and Enums as value types and Classes as reference type.
When you make the LinkedList Class you would very likely create a reference to your node structure. Now struct being a value type, capturing self for value types is dangerous practice and discouraged.
Therefore I would suggest you to create Node as Class and make use of the various access specifiers in Swift to achieve the abstraction you are trying to.
For more details on capturing self in value types you can refer to https://github.com/Wolox/ios-style-guide/blob/master/rules/avoid-struct-closure-self.md.
Details
Xcode 11.3.1, Swift 5.1
Base Interface
Nodeable protocol
import Foundation
protocol Nodeable: class {
associatedtype Value
var value: Value { get set }
var next: Self? { get set }
init(value: Value, next: Self?)
}
// MARK: Extensions
extension Nodeable where Self.Value: Equatable {
static func == (lhs: Self, rhs: Self) -> Bool { lhs.value == rhs.value }
}
extension Nodeable where Self: AnyObject {
var retainCount: Int { CFGetRetainCount(self as CFTypeRef) }
}
extension Nodeable where Self: CustomStringConvertible {
var description: String { return "{ value: \(value), next: \(next == nil ? "nill" : "exist") }" }
}
LinkedListable protocol
import Foundation
protocol LinkedListable where Node.Value == Value {
associatedtype Node: Nodeable
associatedtype Value
var firstNode: Node? { get set }
var lastNode: Node? { get set }
init()
}
extension LinkedListable {
var firstValue: Value? { return firstNode?.value }
var lastValue: Value? { return lastNode?.value }
var isEmpty: Bool { return firstNode == nil }
}
// MARK: Initializers
extension LinkedListable {
init(_ array: [Value]) {
self.init()
array.forEach { append(newLast: $0) }
}
init(copyValuesFrom linkedList: Self) {
self.init()
if linkedList.isEmpty { return }
linkedList.forEachNode { append(newLast: $0.value) }
}
init(copyReferencesFrom linkedList: Self) {
self.init()
firstNode = linkedList.firstNode
lastNode = linkedList.lastNode
}
}
// MARK: Iteration
extension LinkedListable {
func node(at index: Int) -> Node? {
if isEmpty { return nil }
var currentIndex = 0
var resultNode: Node?
forEachWhile {
if index == currentIndex { resultNode = $0; return false }
currentIndex += 1
return true
}
return resultNode
}
func forEachWhile(closure: (Node) -> (Bool)) {
var currentNode = self.firstNode
while currentNode != nil {
guard closure(currentNode!) else { return }
currentNode = currentNode?.next
}
}
func forEachNode(closure: (Node) -> ()) {
forEachWhile { closure($0); return true }
}
}
// MARK: Add/Get values
extension LinkedListable {
func value(at index: Int) -> Value? { node(at: index)?.value }
// MARK: Add new node to the end of list
mutating func append(newLast value: Value) {
let newNode = Node(value: value, next: nil)
if firstNode == nil {
firstNode = newNode
lastNode = firstNode
} else {
lastNode?.next = newNode
lastNode = lastNode?.next
}
}
}
LinkedListable protocol extensions
// MARK: CustomStringConvertible
extension LinkedListable where Self: CustomStringConvertible {
var description: String {
var values = [String]()
forEachNode { values.append("\($0.value)") }
return values.joined(separator: ", ")
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: ExpressibleByArrayLiteral
extension LinkedListable where Self: ExpressibleByArrayLiteral, ArrayLiteralElement == Value {
init(arrayLiteral elements: Self.ArrayLiteralElement...) { self.init(elements) }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Sequence
extension LinkedListable where Self: Sequence {
typealias Iterator = LinkedListableIterator<Node>
func makeIterator() -> LinkedListableIterator<Node> { return .init(firstNode) }
}
struct LinkedListableIterator<Node>: IteratorProtocol where Node: Nodeable {
private var currentNode: Node?
init(_ firstNode: Node?) { self.currentNode = firstNode }
mutating func next() -> Node.Value? {
let node = currentNode
currentNode = currentNode?.next
return node?.value
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Collection
extension LinkedListable where Self: Collection, Self.Index == Int, Self.Element == Value {
var startIndex: Index { 0 }
var endIndex: Index {
guard !isEmpty else { return 0 }
var currentIndex = 0
forEachNode { _ in currentIndex += 1 }
return currentIndex
}
func index(after i: Index) -> Index { i+1 }
subscript(position: Index) -> Element { node(at: position)!.value }
var isEmpty: Bool { return firstNode == nil }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
extension LinkedListable where Self: MutableCollection, Self.Index == Int, Self.Element == Value {
subscript(position: Self.Index) -> Self.Element {
get { return node(at: position)!.value }
set(newValue) { node(at: position)!.value = newValue }
}
}
Usage
implementation of a Node class
import Foundation
final class LinkedListNode<Value>: Nodeable {
var value: Value
var next: LinkedListNode?
init(value: Value, next: LinkedListNode?) {
self.value = value
self.next = next
}
}
extension LinkedListNode: Equatable, CustomStringConvertible where Value: Equatable {}
Implementation of a List class (option 1)
class BaseLinkedList<Value>: LinkedListable where Value: Equatable {
typealias Node = LinkedListNode<Value>
var firstNode: LinkedListNode<Value>?
weak var lastNode: LinkedListNode<Value>?
required init() { }
}
Manipulations with List class (option 1)
var linkedList = BaseLinkedList(["one", "two", "three"])
linkedList = BaseLinkedList(copyReferencesFrom: linkedList)
linkedList = BaseLinkedList(copyValuesFrom: linkedList)
var node = linkedList.firstNode!
print("node value: \(node.value) \(String(describing: node.next))")
node = linkedList.lastNode!
print("node value: \(node.value) \(String(describing: node.next))")
print("isEmpty: \(linkedList.isEmpty)")
linkedList.append(newLast: "four")
linkedList.forEachNode { print($0.value) }
linkedList.forEachNode { print($0.value) }
print("node at index 3: \(String(describing: linkedList.node(at: 3)))")
print("value at index 5: \(String(describing: linkedList.value(at: 4)))")
Implementation of a List class (option 2)
class LinkedList<Value>: BaseLinkedList<Value> where Value: Equatable {}
extension LinkedList: CustomStringConvertible, ExpressibleByArrayLiteral, Sequence, Collection, MutableCollection {}
Manipulations with List class (option 2)
var linkedList = LinkedList(arrayLiteral: "one", "two", "three")
print(linkedList)
print(linkedList.map { $0 + "!" })
print(linkedList.reduce("", { "\($0)_\($1)" }))
linkedList[2] = "five"
print(linkedList[2])
print(linkedList.count)
Some unit tests
import XCTest
// MARK: Test basic List functionality
class TestBasicList: XCTestCase {
typealias LinkedList = BaseLinkedList<Int>
// typealias Value = Int
private var linkedList: LinkedList!
private var possibleValues: [LinkedList.Value] { [1, 2, 3, 4] }
override func setUp() { linkedList = LinkedList() }
func testInitListFromArray() {
TestBasicList.assertCollectionsContainsSameValues(linkedList: LinkedList(possibleValues), array: possibleValues)
}
func testInitListByCopyingValuesFromAnotherList() {
linkedList = .init(possibleValues)
let copiedLinkedList = LinkedList(copyValuesFrom: linkedList)
assertCollections(linkedList1: linkedList, linkedList2: copiedLinkedList, containEqualValues: true)
assertCollections(linkedList1: linkedList, linkedList2: copiedLinkedList, containsSameReferencesToNodes: false)
}
func testInitListByCopyingElementsReferencesFromAnotherList() {
linkedList = .init(possibleValues)
let copiedLinkedList = LinkedList(copyReferencesFrom: linkedList)
assertCollections(linkedList1: linkedList, linkedList2: copiedLinkedList, containEqualValues: true)
assertCollections(linkedList1: linkedList, linkedList2: copiedLinkedList, containsSameReferencesToNodes: true)
}
func testPushFunctionality() {
possibleValues.forEach { linkedList.append(newLast: $0) }
TestBasicList.assertCollectionsContainsSameValues(linkedList: linkedList, array: possibleValues)
}
func testRandomAccess() {
linkedList = .init(possibleValues)
(0 ..< possibleValues.count).forEach {
XCTAssertEqual(possibleValues[$0], linkedList.node(at: $0)?.value)
}
}
private func assertCollections(linkedList1: LinkedList, linkedList2: LinkedList, containEqualValues: Bool) {
var values1 = [LinkedList.Value]()
linkedList1.forEachNode { values1.append($0.value) }
var values2 = [LinkedList.Value]()
linkedList2.forEachNode { values2.append($0.value) }
if containEqualValues {
XCTAssertEqual(values1, values2)
} else {
XCTAssertNotEqual(values1, values2)
}
}
private func assertCollections(linkedList1: LinkedList, linkedList2: LinkedList, containsSameReferencesToNodes: Bool) {
var values1 = [LinkedList.Node]()
linkedList1.forEachNode { values1.append($0) }
var values2 = [LinkedList.Node]()
linkedList2.forEachNode { values2.append($0) }
var areSame: Bool!
for i in 0 ..< values1.count {
areSame = values1[i] === values2[i]
if containsSameReferencesToNodes {
XCTAssertTrue(areSame)
} else {
XCTAssertFalse(areSame)
}
}
}
}
extension TestBasicList {
class func assertCollectionsContainsSameValues<List: LinkedListable>(linkedList: List, array: [List.Value]) where List.Value: Equatable {
var values = [List.Value]()
linkedList.forEachNode { values.append($0.value) }
XCTAssertEqual(values, array)
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Sequence
class LinkedListSequence<Value>: BaseLinkedList<Value>, Sequence where Value: Equatable {}
protocol LinkedListSequenceTestable {
typealias Value = Int
typealias LinkedList = LinkedListSequence<Value>
var linkedList: LinkedList { get set }
var possibleValues: [Value] { get}
}
extension LinkedListSequenceTestable {
func _testFilter() {
XCTAssertEqual(linkedList.filter ({ $0 % 2 == 0 }),
possibleValues.filter({ $0 % 2 == 0 }))
}
func _testMap() {
guard let num = possibleValues.first else { return }
XCTAssertEqual(linkedList.map({ $0 + num}), possibleValues.map({ $0 + num}))
}
func _testCompactMap() {
let array1 = linkedList.compactMap { value -> String? in
if value % 2 != 0 { return "\(value)" }
return nil
}
let array2 = possibleValues.compactMap { value -> String? in
if value % 2 != 0 { return "\(value)" }
return nil
}
XCTAssertEqual(array1, array2)
}
func _testReduce() {
let result1 = linkedList.reduce(LinkedList.Element()) { $0 + $1 }
let result2 = possibleValues.reduce(LinkedList.Element()) { $0 + $1 }
XCTAssertEqual(result1, result2)
}
func _testForEach() {
var values1 = [LinkedList.Value]()
linkedList.forEach { values1.append($0) }
var values2 = [LinkedList.Value]()
possibleValues.forEach { values2.append($0) }
XCTAssertEqual(values1, values2)
}
}
class TestLinkedListSequence_nonEmpty: XCTestCase, LinkedListSequenceTestable {
var linkedList = LinkedList()
var possibleValues: [Value] { [1, 2, 3, 4] }
override func setUp() { linkedList = LinkedList(possibleValues) }
func testFilter() { _testFilter() }
func testMap() { _testMap() }
func testCompactMap() { _testCompactMap() }
func testReduce() { _testReduce() }
func testForEach() { _testForEach() }
}
class TestLinkedListSequence_oneElement: TestLinkedListSequence_nonEmpty {
override var possibleValues: [Value] { [1] }
}
class TestLinkedListSequence_empty: TestLinkedListSequence_nonEmpty {
override var possibleValues: [Value] { [] }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Collection
class LinkedListCollection<Value>: BaseLinkedList<Value>, Sequence, Collection where Value: Equatable {}
protocol LinkedListCollectionTestable {
associatedtype Value: Equatable
typealias LinkedList = LinkedListCollection<Value>
var linkedList: LinkedList { get set }
var possibleValues: [Value] { get}
}
extension LinkedListCollectionTestable {
func _testCount() {
XCTAssertEqual(linkedList.count, possibleValues.count)
}
func _testIsEmpty() {
XCTAssertEqual(linkedList.isEmpty, possibleValues.isEmpty)
XCTAssertEqual(LinkedList().isEmpty, [].isEmpty)
}
func _testIndexes() {
for i in 0 ..< linkedList.count {
XCTAssertEqual(linkedList.index(after: i), possibleValues.index(after: i))
}
}
}
class TestLinkedListCollection_nonEmpty: XCTestCase, LinkedListCollectionTestable {
typealias LinkedList = LinkedListCollection<Int>
var linkedList = LinkedList()
var possibleValues: [LinkedList.Value] { [1, 2, 3, 4] }
override func setUp() { linkedList = LinkedList(possibleValues) }
func testCount() { _testCount() }
func testIsEmpty() { _testIsEmpty() }
func testIndexes() { _testIndexes() }
}
class TestLinkedListCollection_oneElement: TestLinkedListCollection_nonEmpty {
override var possibleValues: [LinkedList.Value] { [1] }
}
class TestLinkedListCollection_empty: TestLinkedListCollection_nonEmpty {
override var possibleValues: [LinkedList.Value] { [] }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: RangeReplaceableCollection
class LinkedListMutableCollection<Value>: BaseLinkedList<Value>, Sequence, Collection, MutableCollection where Value: Equatable & Comparable {}
protocol LinkedListMutableCollectionTestable {
associatedtype Value: Equatable & Comparable
typealias LinkedList = LinkedListMutableCollection<Value>
var linkedList: LinkedList { get set }
var possibleValues: [Value] { get}
}
extension LinkedListMutableCollectionTestable {
func _testSorted() {
XCTAssertEqual(linkedList.sorted(by: { $0 > $1 }),
possibleValues.sorted(by: { $0 > $1 }))
}
func _testSubscriptReading() {
for (index, value) in possibleValues.enumerated() {
XCTAssertEqual(linkedList[index], value)
}
}
func _testSubscriptWriting() {
var list = linkedList
var testArray = possibleValues
TestBasicList.assertCollectionsContainsSameValues(linkedList: linkedList, array: testArray)
for (index, value) in possibleValues.reversed().enumerated() {
testArray[index] = value
list[index] = value
XCTAssertEqual(linkedList[index], testArray[index])
}
print(testArray)
TestBasicList.assertCollectionsContainsSameValues(linkedList: linkedList, array: testArray)
}
}
class TestLinkedListMutableCollection_nonEmptyCollection: XCTestCase, LinkedListMutableCollectionTestable {
typealias LinkedList = LinkedListMutableCollection<Int>
var linkedList = LinkedList()
var possibleValues: [LinkedList.Value] { [1, 3, 2, 4] }
override func setUp() { linkedList = LinkedList(possibleValues) }
func testSorted() { _testSorted() }
func testSubscriptReading() { _testSubscriptReading() }
func testSubscriptWriting() { _testSubscriptWriting() }
}
class TestLinkedListMutableCollection_oneElement: TestLinkedListMutableCollection_nonEmptyCollection {
override var possibleValues: [LinkedList.Value] { [1] }
}
class TestLinkedListMutableCollection_empty: TestLinkedListMutableCollection_nonEmptyCollection {
override var possibleValues: [LinkedList.Value] { [] }
}
Custom LinkedList Type
Xcode 10.2.1, Swift 5.0
My LinkedList type implements all of the following protocols:
CustomStringConvertible
ExpressibleByArrayLiteral
Sequence
Collection
MutableCollection
RangeReplaceableCollection
BidirectionalCollection
As well, it keeps its node type private so the user never needs to know anything of its existence.
This implementation is a doubly linked list so to efficiently enable bidirectional traversal.
Code:
public struct LinkedList<Element> {
private var headNode: Node?
private var tailNode: Node?
public private(set) var count: Int = 0
private var id = ID()
public init() { }
fileprivate class ID {
init() { }
}
}
//MARK: - LinkedList Node
extension LinkedList {
fileprivate class Node {
public var value: Element
public var next: Node?
public weak var previous: Node?
public init(value: Element) {
self.value = value
}
}
}
//MARK: - Initializers
public extension LinkedList {
private init(_ nodeChain: (head: Node, tail: Node, count: Int)?) {
guard let chain = nodeChain else {
return
}
headNode = chain.head
tailNode = chain.tail
count = chain.count
}
init<S>(_ sequence: S) where S: Sequence, S.Element == Element {
if let linkedList = sequence as? LinkedList<Element> {
self = linkedList
} else {
self = LinkedList(chain(of: sequence))
}
}
}
//MARK: Chain of Nodes
extension LinkedList {
// Creates a chain of nodes from a sequence. Returns `nil` if the sequence is empty.
private func chain<S>(of sequence: S) -> (head: Node, tail: Node, count: Int)? where S: Sequence, S.Element == Element {
var iterator = sequence.makeIterator()
var head, tail: Node
var count = 0
guard let firstValue = iterator.next() else {
return nil
}
var currentNode = Node(value: firstValue)
head = currentNode
count = 1
while let nextElement = iterator.next() {
let nextNode = Node(value: nextElement)
currentNode.next = nextNode
nextNode.previous = currentNode
currentNode = nextNode
count += 1
}
tail = currentNode
return (head: head, tail: tail, count: count)
}
}
//MARK: - Copy Nodes
extension LinkedList {
private mutating func copyNodes(settingNodeAt index: Index, to value: Element) {
var currentIndex = startIndex
var currentNode = Node(value: currentIndex == index ? value : currentIndex.node!.value)
let newHeadNode = currentNode
currentIndex = self.index(after: currentIndex)
while currentIndex < endIndex {
let nextNode = Node(value: currentIndex == index ? value : currentIndex.node!.value)
currentNode.next = nextNode
nextNode.previous = currentNode
currentNode = nextNode
currentIndex = self.index(after: currentIndex)
}
headNode = newHeadNode
tailNode = currentNode
}
#discardableResult
private mutating func copyNodes(removing range: Range<Index>) -> Range<Index> {
id = ID()
var currentIndex = startIndex
while range.contains(currentIndex) {
currentIndex = index(after: currentIndex)
}
guard let headValue = currentIndex.node?.value else {
self = LinkedList()
return endIndex..<endIndex
}
var currentNode = Node(value: headValue)
let newHeadNode = currentNode
var newCount = 1
var removedRange: Range<Index> = Index(node: currentNode, offset: 0, id: id)..<Index(node: currentNode, offset: 0, id: id)
currentIndex = index(after: currentIndex)
while currentIndex < endIndex {
guard !range.contains(currentIndex) else {
currentIndex = index(after: currentIndex)
continue
}
let nextNode = Node(value: currentIndex.node!.value)
if currentIndex == range.upperBound {
removedRange = Index(node: nextNode, offset: newCount, id: id)..<Index(node: nextNode, offset: newCount, id: id)
}
currentNode.next = nextNode
nextNode.previous = currentNode
currentNode = nextNode
newCount += 1
currentIndex = index(after: currentIndex)
}
if currentIndex == range.upperBound {
removedRange = Index(node: nil, offset: newCount, id: id)..<Index(node: nil, offset: newCount, id: id)
}
headNode = newHeadNode
tailNode = currentNode
count = newCount
return removedRange
}
}
//MARK: - Computed Properties
public extension LinkedList {
var head: Element? {
return headNode?.value
}
var tail: Element? {
return tailNode?.value
}
}
//MARK: - Sequence Conformance
extension LinkedList: Sequence {
public typealias Element = Element
public __consuming func makeIterator() -> Iterator {
return Iterator(node: headNode)
}
public struct Iterator: IteratorProtocol {
private var currentNode: Node?
fileprivate init(node: Node?) {
currentNode = node
}
public mutating func next() -> Element? {
guard let node = currentNode else {
return nil
}
currentNode = node.next
return node.value
}
}
}
//MARK: - Collection Conformance
extension LinkedList: Collection {
public var startIndex: Index {
return Index(node: headNode, offset: 0, id: id)
}
public var endIndex: Index {
return Index(node: nil, offset: count, id: id)
}
public var first: Element? {
return head
}
public var isEmpty: Bool {
return count == 0
}
public func index(after i: Index) -> Index {
precondition(i.listID === self.id, "LinkedList index is invalid")
precondition(i.offset != endIndex.offset, "LinkedList index is out of bounds")
return Index(node: i.node?.next, offset: i.offset + 1, id: id)
}
public struct Index: Comparable {
fileprivate weak var node: Node?
fileprivate var offset: Int
fileprivate weak var listID: ID?
fileprivate init(node: Node?, offset: Int, id: ID) {
self.node = node
self.offset = offset
self.listID = id
}
public static func ==(lhs: Index, rhs: Index) -> Bool {
return lhs.offset == rhs.offset
}
public static func <(lhs: Index, rhs: Index) -> Bool {
return lhs.offset < rhs.offset
}
}
}
//MARK: - MutableCollection Conformance
extension LinkedList: MutableCollection {
public subscript(position: Index) -> Element {
get {
precondition(position.listID === self.id, "LinkedList index is invalid")
precondition(position.offset != endIndex.offset, "Index out of range")
guard let node = position.node else {
preconditionFailure("LinkedList index is invalid")
}
return node.value
}
set {
precondition(position.listID === self.id, "LinkedList index is invalid")
precondition(position.offset != endIndex.offset, "Index out of range")
// Copy-on-write semantics for nodes
if !isKnownUniquelyReferenced(&headNode) {
copyNodes(settingNodeAt: position, to: newValue)
} else {
position.node?.value = newValue
}
}
}
}
//MARK: LinkedList Specific Operations
public extension LinkedList {
mutating func prepend(_ newElement: Element) {
replaceSubrange(startIndex..<startIndex, with: CollectionOfOne(newElement))
}
mutating func prepend<S>(contentsOf newElements: __owned S) where S: Sequence, S.Element == Element {
replaceSubrange(startIndex..<startIndex, with: newElements)
}
#discardableResult
mutating func popFirst() -> Element? {
if isEmpty {
return nil
}
return removeFirst()
}
#discardableResult
mutating func popLast() -> Element? {
if isEmpty {
return nil
}
return removeLast()
}
}
//MARK: - BidirectionalCollection Conformance
extension LinkedList: BidirectionalCollection {
public var last: Element? {
return tail
}
public func index(before i: Index) -> Index {
precondition(i.listID === self.id, "LinkedList index is invalid")
precondition(i.offset != startIndex.offset, "LinkedList index is out of bounds")
if i.offset == count {
return Index(node: tailNode, offset: i.offset - 1, id: id)
}
return Index(node: i.node?.previous, offset: i.offset - 1, id: id)
}
}
//MARK: - RangeReplaceableCollection Conformance
extension LinkedList: RangeReplaceableCollection {
public mutating func append<S>(contentsOf newElements: __owned S) where S: Sequence, Element == S.Element {
replaceSubrange(endIndex..<endIndex, with: newElements)
}
public mutating func replaceSubrange<S, R>(_ subrange: R, with newElements: __owned S) where S: Sequence, R: RangeExpression, Element == S.Element, Index == R.Bound {
var range = subrange.relative(to: indices)
precondition(range.lowerBound.listID === id && range.upperBound.listID === id, "LinkedList range of indices are invalid")
precondition(range.lowerBound >= startIndex && range.upperBound <= endIndex, "Subrange bounds are out of range")
// If range covers all elements and the new elements are a LinkedList then set references to it
if range.lowerBound == startIndex, range.upperBound == endIndex, let linkedList = newElements as? LinkedList {
self = linkedList
return
}
var newElementsCount = 0
// There are no new elements, so range indicates deletion
guard let nodeChain = chain(of: newElements) else {
// If there is nothing in the removal range
// This also covers the case that the linked list is empty because this is the only possible range
guard range.lowerBound != range.upperBound else {
return
}
// Deletion range spans all elements
if range.lowerBound == startIndex && range.upperBound == endIndex {
headNode = nil
tailNode = nil
count = 0
return
}
// Copy-on-write semantics for nodes and remove elements in range
guard isKnownUniquelyReferenced(&headNode) else {
copyNodes(removing: range)
return
}
// Update count after mutation to preserve startIndex and endIndex validity
defer {
count = count - (range.upperBound.offset - range.lowerBound.offset)
}
// Move head up if deletion starts at start index
if range.lowerBound == startIndex {
// Can force unwrap node since the upperBound is not the end index
headNode = range.upperBound.node!
headNode!.previous = nil
// Move tail back if deletion ends at end index
} else if range.upperBound == endIndex {
// Can force unwrap since lowerBound index must have an associated element
tailNode = range.lowerBound.node!.previous
tailNode!.next = nil
// Deletion range is in the middle of the linked list
} else {
// Can force unwrap all bound nodes since they both must have elements
range.upperBound.node!.previous = range.lowerBound.node!.previous
range.lowerBound.node!.previous!.next = range.upperBound.node!
}
return
}
// Obtain the count of the new elements from the node chain composed from them
newElementsCount = nodeChain.count
// Replace entire content of list with new elements
if range.lowerBound == startIndex && range.upperBound == endIndex {
headNode = nodeChain.head
tailNode = nodeChain.tail
count = nodeChain.count
return
}
// Copy-on-write semantics for nodes before mutation
if !isKnownUniquelyReferenced(&headNode) {
range = copyNodes(removing: range)
}
// Update count after mutation to preserve startIndex and endIndex validity
defer {
count += nodeChain.count - (range.upperBound.offset - range.lowerBound.offset)
}
// Prepending new elements
guard range.upperBound != startIndex else {
headNode?.previous = nodeChain.tail
nodeChain.tail.next = headNode
headNode = nodeChain.head
return
}
// Appending new elements
guard range.lowerBound != endIndex else {
tailNode?.next = nodeChain.head
nodeChain.head.previous = tailNode
tailNode = nodeChain.tail
return
}
if range.lowerBound == startIndex {
headNode = nodeChain.head
}
if range.upperBound == endIndex {
tailNode = nodeChain.tail
}
range.lowerBound.node!.previous!.next = nodeChain.head
range.upperBound.node!.previous = nodeChain.tail
}
}
//MARK: - ExpressibleByArrayLiteral Conformance
extension LinkedList: ExpressibleByArrayLiteral {
public typealias ArrayLiteralElement = Element
public init(arrayLiteral elements: ArrayLiteralElement...) {
self.init(elements)
}
}
//MARK: - CustomStringConvertible Conformance
extension LinkedList: CustomStringConvertible {
public var description: String {
return "[" + lazy.map { "\($0)" }.joined(separator: ", ") + "]"
}
}
//MARK: - Equatable Conformance
extension LinkedList: Equatable where Element: Equatable {
public static func ==(lhs: LinkedList<Element>, rhs: LinkedList<Element>) -> Bool {
for (a, b) in zip(lhs, rhs) {
guard a == b else {
return false
}
}
return true
}
}
If you'd like to use this type fully-documented in your own project, feel free to download it or add it as a dependency with Swift PM by checking out my LinkedList GitHub repository.
This is not really a good question for Stack Overflow, but I will answer anyway. Here is a super basic implementation of a singly linked list:
class Node {
let value: Int
var next: Node?
init(value: Int, next: Node? = nil) {
self.value = value
self.next = next
}
}
class LinkedList {
let head: Node
init(node: Node) {
self.head = node
}
convenience init(nodeValue: Int) {
self.init(node: Node(value: nodeValue))
}
func addNode(node: Node) {
var current: Node = self.head
while current.next != nil {
current = current.next!
}
current.next = node
}
func addNode(withValue value: Int) {
self.addNode(node: Node(value: value))
}
}
let list = LinkedList(nodeValue: 4)
list.addNode(withValue: 3)
list.addNode(withValue: 8)
//The list is now [ 4 ]->[ 3 ]->[ 8 ]
Hopefully I can clarify a few points.
Can anyone tell me how to create a linked-list in swift with node as
structure and linked-list as class.
The node essentially is the structure. As other people have pointed out, a linked list is nothing more than a very basic data type (often called a Node) that holds a value and a reference to another Node.
The code posted above is a linked list:
class Node {
let value: Int
var next: Node?
init(value: Int, next: Node? = nil) {
self.value = value
self.next = next
}
}
Think of a link in a chain. This is your Node.
Think of a couple of links together. This is your linked list.
My point here is that there is nothing additional. By having the ability to make a single Node, you have the ability to make a linked list (just a bunch of Nodes connected).
I tried to create a node Node with reference to itself and faced a
error "value type 'Node' cannot have a stored property that references
itself"
Others have explained why this won't work.
for resolving it i created one more class Next and now I am unable to
proceed further.
Please don't do this. Your next node is just another Node. This is completely unnecessary.
Sometimes you will see a linked list class that holds a Node. This is just to help you manipulate the list a little easier. So when you say
linked-list as class
I'm pretty sure you're just referring to a collection of functions that help manipulate your list. These can just as easily be standalone functions that take a Node and operate on it.
For instance to add a link to the chain you can have a function add(value: Value, to list: Node). A function like this may or may not exist on some arbitrary LinkedList class. It often does but probably should not.
func append(_ node: Node, to list: Node) {
var current = list
while let nextNode = current.next {
current = nextNode
}
current.next = node
}
Hope this helps!
Checked on XCode 10 playground - Swift 4.2
class Node {
let value: Int
var next: Node?
init(value: Int, next: Node? = nil) {
self.value = value
self.next = next
}
}
class LinkedList {
let head: Node
init(node: Node) {
self.head = node
}
convenience init(nodeValue: Int) {
self.init(node: Node(value: nodeValue))
}
func addNode(node: Node) {
var current: Node = self.head
while current.next != nil {
current = current.next!
}
current.next = node
}
func addNode(withValue value: Int) {
self.addNode(node: Node(value: value))
}
func traverse() -> [Int]{
var results: [Int] = []
var current: Node = self.head
while current.next != nil {
current = current.next!
results.append(current.value)
}
return results
}
}
let list = LinkedList(nodeValue: 4)
list.addNode(withValue: 3)
list.addNode(withValue: 8)
list.addNode(withValue: 8)
list.addNode(withValue: 8)
list.addNode(withValue: 8)
list.traverse()
A workaround that I can think of is to describe the linked list node as a protocol and then create a struct that confirms that protocol
protocol LinkedNode {
var value: Int { get }
var next: LinkedListNode? { get }
}
struct Node: LinkedNode {
let value: Int
let next: LinkedListNode?
}
let linkedList = Node(value: 2, next: Node(value: 4, next: nil))
I have a variable that takes the number of objects in the array in a different class, how can I keep track of the change of this variable in the current class? I did a lot of different attempts but failed.
var digitIndex: Int! {
set {
self.digitIndex = newValue
}
get {
return firstClass.indexesOfSelectedNodes().count
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &digitIndex {
if let newValue = change?[NSKeyValueChangeNewKey] {
print("newValue")
infoLabel.text = "\(newValue)"
}
}
}
1) in your code
var digitIndex: Int! {
set {
self.digitIndex = newValue
}
get {
return firstClass.indexesOfSelectedNodes().count
}
}
digitIndex is computed property! You are not able to set self.digitIndex within its own setter!
this code, even though compiled, will run forever :-)
var i: Int {
get {
return 10
}
set {
i = newValue
}
}
i = 100
print(i)
2) How to use willSet and didSet (for STORED properties)?
class C1 {}
class C2 {}
class C {
var objects: [AnyObject] = [C1(),C1(),C2()] {
willSet {
print(objects, objects.count, newValue)
}
didSet {
print(objects, objects.count)
}
}
func add(object: AnyObject) {
objects.append(object)
}
}
let c = C()
c.add(C1())
/*
[C1, C1, C2] 3 [C1, C1, C2, C1]
[C1, C1, C2, C1] 4
*/
var i: Int = 0 {
willSet {
print(newValue, "will replace", i)
}
didSet {
print(oldValue, "was replaced by", i)
}
}
i = 100
/*
100 will replace 0
0 was replaced by 100
*/
you could combine the computed and stored properties for your advantage
// 'private' storage
var _j:Int = 0
var j: Int {
get {
return _j
}
set {
print(newValue)
if newValue < 300 {
_j = newValue
} else {
print(newValue, "refused")
}
}
}
print(j) // prints 0
j = 200 // prints 200
print(j) // prints 200
j = 500 // prints 500 refused
print(j) // prints 200
Try this :
var digitIndex: Int! {
set {
self.digitIndex = newValue
}
get {
return firstClass.indexesOfSelectedNodes().count
}
didSet {
//you will get new value here
}
}
No need to add observer for our class properties, you just required to add observer for the properties provided by super class.
You can make use of a delegate handling the communication between your two classes.
An example follows below, using a custom delegate MyDelegate (protocol). A delegate instance is initialized in MyOtherClass (e.g., a view controller class), which makes a delegate callback whenever the array myArr is updated in this class. This, in turn, updates the value of digitIndex in MyCurrentClass (e.g., some custom control), which conforms to MyDelegate by implementing the blueprinted arrUpdated(..) method. Finally, the didSet property observer on digitIndex in MyCurrentClass tells us via console print-out that its value has been updated.
protocol MyDelegate: class {
func arrUpdated(arr: [Int])
}
class MyDifferentClass {
private var myArr : [Int] = [] {
didSet {
// Call delegate.
delegate?.arrUpdated(myArr)
}
}
weak var delegate: MyDelegate?
}
class MyCurrentClass: MyDelegate {
var myDifferentClass : MyDifferentClass
var digitIndex: Int = 0 {
didSet {
print("digitIndex updated: \(digitIndex)")
}
}
init(a: MyDifferentClass) {
myDifferentClass = a
myDifferentClass.delegate = self
}
// MyDelegate
func arrUpdated(arr: [Int]) {
digitIndex = arr.count
}
}
Test:
var a = MyDifferentClass()
var b = MyCurrentClass(a: a)
a.myArr.append(1) // prints 'digitIndex updated: 1'
I am switching an application from Objective-C to Swift, which I have a couple of categories with stored properties, for example:
#interface UIView (MyCategory)
- (void)alignToView:(UIView *)view
alignment:(UIViewRelativeAlignment)alignment;
- (UIView *)clone;
#property (strong) PFObject *xo;
#property (nonatomic) BOOL isAnimating;
#end
As Swift extensions don't accept stored properties like these, I don't know how to maintain the same structure as the Objc code. Stored properties are really important for my app and I believe Apple must have created some solution for doing it in Swift.
As said by jou, what I was looking for was actually using associated objects, so I did (in another context):
import Foundation
import QuartzCore
import ObjectiveC
extension CALayer {
var shapeLayer: CAShapeLayer? {
get {
return objc_getAssociatedObject(self, "shapeLayer") as? CAShapeLayer
}
set(newValue) {
objc_setAssociatedObject(self, "shapeLayer", newValue, UInt(OBJC_ASSOCIATION_RETAIN))
}
}
var initialPath: CGPathRef! {
get {
return objc_getAssociatedObject(self, "initialPath") as CGPathRef
}
set {
objc_setAssociatedObject(self, "initialPath", newValue, UInt(OBJC_ASSOCIATION_RETAIN))
}
}
}
But I get an EXC_BAD_ACCESS when doing:
class UIBubble : UIView {
required init(coder aDecoder: NSCoder) {
...
self.layer.shapeLayer = CAShapeLayer()
...
}
}
Any ideas?
As in Objective-C, you can't add stored property to existing classes. If you're extending an Objective-C class (UIView is definitely one), you can still use Associated Objects to emulate stored properties:
for Swift 1
import ObjectiveC
private var xoAssociationKey: UInt8 = 0
extension UIView {
var xo: PFObject! {
get {
return objc_getAssociatedObject(self, &xoAssociationKey) as? PFObject
}
set(newValue) {
objc_setAssociatedObject(self, &xoAssociationKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN))
}
}
}
The association key is a pointer that should be the unique for each association. For that, we create a private global variable and use it's memory address as the key with the & operator. See the Using Swift with Cocoa and Objective-C
on more details how pointers are handled in Swift.
UPDATED for Swift 2 and 3
import ObjectiveC
private var xoAssociationKey: UInt8 = 0
extension UIView {
var xo: PFObject! {
get {
return objc_getAssociatedObject(self, &xoAssociationKey) as? PFObject
}
set(newValue) {
objc_setAssociatedObject(self, &xoAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
}
UPDATED for Swift 4
In Swift 4, it's much more simple. The Holder struct will contain the private value that our computed property will expose to the world, giving the illusion of a stored property behaviour instead.
Source
extension UIViewController {
struct Holder {
static var _myComputedProperty:Bool = false
}
var myComputedProperty:Bool {
get {
return Holder._myComputedProperty
}
set(newValue) {
Holder._myComputedProperty = newValue
}
}
}
Associated objects API is a bit cumbersome to use. You can remove most of the boilerplate with a helper class.
public final class ObjectAssociation<T: AnyObject> {
private let policy: objc_AssociationPolicy
/// - Parameter policy: An association policy that will be used when linking objects.
public init(policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN_NONATOMIC) {
self.policy = policy
}
/// Accesses associated object.
/// - Parameter index: An object whose associated object is to be accessed.
public subscript(index: AnyObject) -> T? {
get { return objc_getAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque()) as! T? }
set { objc_setAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque(), newValue, policy) }
}
}
Provided that you can "add" a property to objective-c class in a more readable manner:
extension SomeType {
private static let association = ObjectAssociation<NSObject>()
var simulatedProperty: NSObject? {
get { return SomeType.association[self] }
set { SomeType.association[self] = newValue }
}
}
As for the solution:
extension CALayer {
private static let initialPathAssociation = ObjectAssociation<CGPath>()
private static let shapeLayerAssociation = ObjectAssociation<CAShapeLayer>()
var initialPath: CGPath! {
get { return CALayer.initialPathAssociation[self] }
set { CALayer.initialPathAssociation[self] = newValue }
}
var shapeLayer: CAShapeLayer? {
get { return CALayer.shapeLayerAssociation[self] }
set { CALayer.shapeLayerAssociation[self] = newValue }
}
}
So I think I found a method that works cleaner than the ones above because it doesn't require any global variables. I got it from here:
http://nshipster.com/swift-objc-runtime/
The gist is that you use a struct like so:
extension UIViewController {
private struct AssociatedKeys {
static var DescriptiveName = "nsh_DescriptiveName"
}
var descriptiveName: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.DescriptiveName,
newValue as NSString?,
UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)
)
}
}
}
}
UPDATE for Swift 2
private struct AssociatedKeys {
static var displayed = "displayed"
}
//this lets us check to see if the item is supposed to be displayed or not
var displayed : Bool {
get {
guard let number = objc_getAssociatedObject(self, &AssociatedKeys.displayed) as? NSNumber else {
return true
}
return number.boolValue
}
set(value) {
objc_setAssociatedObject(self,&AssociatedKeys.displayed,NSNumber(bool: value),objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
The solution pointed out by jou doesn't support value types,
this works fine with them as well
Wrappers
import ObjectiveC
final class Lifted<T> {
let value: T
init(_ x: T) {
value = x
}
}
private func lift<T>(x: T) -> Lifted<T> {
return Lifted(x)
}
func setAssociatedObject<T>(object: AnyObject, value: T, associativeKey: UnsafePointer<Void>, policy: objc_AssociationPolicy) {
if let v: AnyObject = value as? AnyObject {
objc_setAssociatedObject(object, associativeKey, v, policy)
}
else {
objc_setAssociatedObject(object, associativeKey, lift(value), policy)
}
}
func getAssociatedObject<T>(object: AnyObject, associativeKey: UnsafePointer<Void>) -> T? {
if let v = objc_getAssociatedObject(object, associativeKey) as? T {
return v
}
else if let v = objc_getAssociatedObject(object, associativeKey) as? Lifted<T> {
return v.value
}
else {
return nil
}
}
A possible
Class extension (Example of usage):
extension UIView {
private struct AssociatedKey {
static var viewExtension = "viewExtension"
}
var referenceTransform: CGAffineTransform? {
get {
return getAssociatedObject(self, associativeKey: &AssociatedKey.viewExtension)
}
set {
if let value = newValue {
setAssociatedObject(self, value: value, associativeKey: &AssociatedKey.viewExtension, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
}
This is really such a great solution, I wanted to add another usage example that included structs and values that are not optionals. Also, the AssociatedKey values can be simplified.
struct Crate {
var name: String
}
class Box {
var name: String
init(name: String) {
self.name = name
}
}
extension UIViewController {
private struct AssociatedKey {
static var displayed: UInt8 = 0
static var box: UInt8 = 0
static var crate: UInt8 = 0
}
var displayed: Bool? {
get {
return getAssociatedObject(self, associativeKey: &AssociatedKey.displayed)
}
set {
if let value = newValue {
setAssociatedObject(self, value: value, associativeKey: &AssociatedKey.displayed, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
var box: Box {
get {
if let result:Box = getAssociatedObject(self, associativeKey: &AssociatedKey.box) {
return result
} else {
let result = Box(name: "")
self.box = result
return result
}
}
set {
setAssociatedObject(self, value: newValue, associativeKey: &AssociatedKey.box, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var crate: Crate {
get {
if let result:Crate = getAssociatedObject(self, associativeKey: &AssociatedKey.crate) {
return result
} else {
let result = Crate(name: "")
self.crate = result
return result
}
}
set {
setAssociatedObject(self, value: newValue, associativeKey: &AssociatedKey.crate, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
You can't define categories (Swift extensions) with new storage; any additional properties must be computed rather than stored. The syntax works for Objective C because #property in a category essentially means "I'll provide the getter and setter". In Swift, you'll need to define these yourself to get a computed property; something like:
extension String {
public var Foo : String {
get
{
return "Foo"
}
set
{
// What do you want to do here?
}
}
}
Should work fine. Remember, you can't store new values in the setter, only work with the existing available class state.
My $0.02. This code is written in Swift 2.0
extension CALayer {
private struct AssociatedKeys {
static var shapeLayer:CAShapeLayer?
}
var shapeLayer: CAShapeLayer? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.shapeLayer) as? CAShapeLayer
}
set {
if let newValue = newValue {
objc_setAssociatedObject(self, &AssociatedKeys.shapeLayer, newValue as CAShapeLayer?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
}
I have tried many solutions, and found this is the only way to actually extend a class with extra variable parameters.
Why relying on objc runtime? I don't get the point. By using something like the following you will achieve almost the identical behaviour of a stored property, by using only a pure Swift approach:
extension UIViewController {
private static var _myComputedProperty = [String:Bool]()
var myComputedProperty:Bool {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UIViewController._myComputedProperty[tmpAddress] ?? false
}
set(newValue) {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UIViewController._myComputedProperty[tmpAddress] = newValue
}
}
}
I prefer doing code in pure Swift and not rely on Objective-C heritage. Because of this I wrote pure Swift solution with two advantages and two disadvantages.
Advantages:
Pure Swift code
Works on classes and completions or more specifically on Any object
Disadvantages:
Code should call method willDeinit() to release objects linked to specific class instance to avoid memory leaks
You cannot make extension directly to UIView for this exact example because var frame is extension to UIView, not part of class.
EDIT:
import UIKit
var extensionPropertyStorage: [NSObject: [String: Any]] = [:]
var didSetFrame_ = "didSetFrame"
extension UILabel {
override public var frame: CGRect {
get {
return didSetFrame ?? CGRectNull
}
set {
didSetFrame = newValue
}
}
var didSetFrame: CGRect? {
get {
return extensionPropertyStorage[self]?[didSetFrame_] as? CGRect
}
set {
var selfDictionary = extensionPropertyStorage[self] ?? [String: Any]()
selfDictionary[didSetFrame_] = newValue
extensionPropertyStorage[self] = selfDictionary
}
}
func willDeinit() {
extensionPropertyStorage[self] = nil
}
}
With Obj-c Categories you can only add methods, not instance variables.
In you example you have used #property as a shortcut to adding getter and setter method declarations. You still need to implement those methods.
Similarly in Swift you can add use extensions to add instance methods, computed properties etc. but not stored properties.
Notice: after further analyzing, the code below works fine, but does not release the view object, so if I can find a way around it I'll edit the answer. meanwhile, read the comments.
How about storing static map to class that is extending like this :
extension UIView {
struct Holder {
static var _padding:[UIView:UIEdgeInsets] = [:]
}
var padding : UIEdgeInsets {
get{ return UIView.Holder._padding[self] ?? .zero}
set { UIView.Holder._padding[self] = newValue }
}
}
I also get an EXC_BAD_ACCESS problem.The value in objc_getAssociatedObject() and objc_setAssociatedObject() should be an Object. And the objc_AssociationPolicy should match the Object.
I tried using objc_setAssociatedObject as mentioned in a few of the answers here, but after failing with it a few times I stepped back and realized there is no reason I need that. Borrowing from a few of the ideas here, I came up with this code which simply stores an array of whatever my extra data is (MyClass in this example) indexed by the object I want to associate it with:
class MyClass {
var a = 1
init(a: Int)
{
self.a = a
}
}
extension UIView
{
static var extraData = [UIView: MyClass]()
var myClassData: MyClass? {
get {
return UIView.extraData[self]
}
set(value) {
UIView.extraData[self] = value
}
}
}
// Test Code: (Ran in a Swift Playground)
var view1 = UIView()
var view2 = UIView()
view1.myClassData = MyClass(a: 1)
view2.myClassData = MyClass(a: 2)
print(view1.myClassData?.a)
print(view2.myClassData?.a)
Here is simplified and more expressive solution. It works for both value and reference types. The approach of lifting is taken from #HepaKKes answer.
Association code:
import ObjectiveC
final class Lifted<T> {
let value: T
init(_ x: T) {
value = x
}
}
private func lift<T>(_ x: T) -> Lifted<T> {
return Lifted(x)
}
func associated<T>(to base: AnyObject,
key: UnsafePointer<UInt8>,
policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN,
initialiser: () -> T) -> T {
if let v = objc_getAssociatedObject(base, key) as? T {
return v
}
if let v = objc_getAssociatedObject(base, key) as? Lifted<T> {
return v.value
}
let lifted = Lifted(initialiser())
objc_setAssociatedObject(base, key, lifted, policy)
return lifted.value
}
func associate<T>(to base: AnyObject, key: UnsafePointer<UInt8>, value: T, policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN) {
if let v: AnyObject = value as AnyObject? {
objc_setAssociatedObject(base, key, v, policy)
}
else {
objc_setAssociatedObject(base, key, lift(value), policy)
}
}
Example of usage:
1) Create extension and associate properties to it. Let's use both value and reference type properties.
extension UIButton {
struct Keys {
static fileprivate var color: UInt8 = 0
static fileprivate var index: UInt8 = 0
}
var color: UIColor {
get {
return associated(to: self, key: &Keys.color) { .green }
}
set {
associate(to: self, key: &Keys.color, value: newValue)
}
}
var index: Int {
get {
return associated(to: self, key: &Keys.index) { -1 }
}
set {
associate(to: self, key: &Keys.index, value: newValue)
}
}
}
2) Now you can use just as regular properties:
let button = UIButton()
print(button.color) // UIExtendedSRGBColorSpace 0 1 0 1 == green
button.color = .black
print(button.color) // UIExtendedGrayColorSpace 0 1 == black
print(button.index) // -1
button.index = 3
print(button.index) // 3
More details:
Lifting is needed for wrapping value types.
Default associated object behavior is retain. If you want to learn more about associated objects, I'd recommend checking this article.
if you are looking to set a custom string attribute to a UIView, this is how I did it on Swift 4
Create a UIView extension
extension UIView {
func setStringValue(value: String, key: String) {
layer.setValue(value, forKey: key)
}
func stringValueFor(key: String) -> String? {
return layer.value(forKey: key) as? String
}
}
To use this extension
let key = "COLOR"
let redView = UIView()
// To set
redView.setStringAttribute(value: "Red", key: key)
// To read
print(redView.stringValueFor(key: key)) // Optional("Red")
In PURE SWIFT with WEAK reference handling
import Foundation
import UIKit
extension CustomView {
// can make private
static let storedProperties = WeakDictionary<UIView, Properties>()
struct Properties {
var url: String = ""
var status = false
var desc: String { "url: \(url), status: \(status)" }
}
var properties: Properties {
get {
return CustomView.storedProperties.get(forKey: self) ?? Properties()
}
set {
CustomView.storedProperties.set(forKey: self, object: newValue)
}
}
}
var view: CustomView? = CustomView()
print("1 print", view?.properties.desc ?? "nil")
view?.properties.url = "abc"
view?.properties.status = true
print("2 print", view?.properties.desc ?? "nil")
view = nil
WeakDictionary.swift
import Foundation
private class WeakHolder<T: AnyObject>: Hashable {
weak var object: T?
let hash: Int
init(object: T) {
self.object = object
hash = ObjectIdentifier(object).hashValue
}
func hash(into hasher: inout Hasher) {
hasher.combine(hash)
}
static func ==(lhs: WeakHolder, rhs: WeakHolder) -> Bool {
return lhs.hash == rhs.hash
}
}
class WeakDictionary<T1: AnyObject, T2> {
private var dictionary = [WeakHolder<T1>: T2]()
func set(forKey: T1, object: T2?) {
dictionary[WeakHolder(object: forKey)] = object
}
func get(forKey: T1) -> T2? {
let obj = dictionary[WeakHolder(object: forKey)]
return obj
}
func forEach(_ handler: ((key: T1, value: T2)) -> Void) {
dictionary.forEach {
if let object = $0.key.object, let value = dictionary[$0.key] {
handler((object, value))
}
}
}
func clean() {
var removeList = [WeakHolder<T1>]()
dictionary.forEach {
if $0.key.object == nil {
removeList.append($0.key)
}
}
removeList.forEach {
dictionary[$0] = nil
}
}
}
Another example with using Objective-C associated objects and computed properties for Swift 3 and Swift 4
import CoreLocation
extension CLLocation {
private struct AssociatedKeys {
static var originAddress = "originAddress"
static var destinationAddress = "destinationAddress"
}
var originAddress: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.originAddress) as? String
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.originAddress,
newValue as NSString?,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
}
var destinationAddress: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.destinationAddress) as? String
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.destinationAddress,
newValue as NSString?,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
}
}
First, Associated Objects should be the best right solution for the extended stored properties, because it comes from the Objective-C runtime, this is a great powerful feature that we should use before there are other native features of Swift language.
You should always aware that the associated objects will be released after there are no other objects to retain them, including swift objects, so don't use custom containers to retain the target values which won't be released automatically.
Second, for those additional associated key structure definitions, the core functions just need a UnsafeRawPointer for that, actually there is another best choice for that, #function is a static string which generated when compiling the source code, it also has its own address to use.
So, here is it:
var status: Bool? {
get { objc_getAssociatedObject(self, #function) as? Bool }
set { objc_setAssociatedObject(self, #function, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)}
}
Build for swift 5.
Last, keep in mind the object type with the association policy.
I tried to store properties by using objc_getAssociatedObject, objc_setAssociatedObject, without any luck. My goal was create extension for UITextField, to validate text input characters length.
Following code works fine for me. Hope this will help someone.
private var _min: Int?
private var _max: Int?
extension UITextField {
#IBInspectable var minLength: Int {
get {
return _min ?? 0
}
set {
_min = newValue
}
}
#IBInspectable var maxLength: Int {
get {
return _max ?? 1000
}
set {
_max = newValue
}
}
func validation() -> (valid: Bool, error: String) {
var valid: Bool = true
var error: String = ""
guard let text = self.text else { return (true, "") }
if text.characters.count < minLength {
valid = false
error = "Textfield should contain at least \(minLength) characters"
}
if text.characters.count > maxLength {
valid = false
error = "Textfield should not contain more then \(maxLength) characters"
}
if (text.characters.count < minLength) && (text.characters.count > maxLength) {
valid = false
error = "Textfield should contain at least \(minLength) characters\n"
error = "Textfield should not contain more then \(maxLength) characters"
}
return (valid, error)
}
}
Why not just do something like this, i see other solutions are way out of the small need.
private var optionalID: String {
UUID().uuidString
}
Here is an alternative that works also
public final class Storage : AnyObject {
var object:Any?
public init(_ object:Any) {
self.object = object
}
}
extension Date {
private static let associationMap = NSMapTable<NSString, AnyObject>()
private struct Keys {
static var Locale:NSString = "locale"
}
public var locale:Locale? {
get {
if let storage = Date.associationMap.object(forKey: Keys.Locale) {
return (storage as! Storage).object as? Locale
}
return nil
}
set {
if newValue != nil {
Date.associationMap.setObject(Storage(newValue), forKey: Keys.Locale)
}
}
}
}
var date = Date()
date.locale = Locale(identifier: "pt_BR")
print( date.locale )
I found this solution more practical
UPDATED for Swift 3
extension UIColor {
static let graySpace = UIColor.init(red: 50/255, green: 50/255, blue: 50/255, alpha: 1.0)
static let redBlood = UIColor.init(red: 102/255, green: 0/255, blue: 0/255, alpha: 1.0)
static let redOrange = UIColor.init(red: 204/255, green: 17/255, blue: 0/255, alpha: 1.0)
func alpha(value : CGFloat) -> UIColor {
var r = CGFloat(0), g = CGFloat(0), b = CGFloat(0), a = CGFloat(0)
self.getRed(&r, green: &g, blue: &b, alpha: &a)
return UIColor(red: r, green: g, blue: b, alpha: value)
}
}
...then in your code
class gameController: UIViewController {
#IBOutlet var game: gameClass!
override func viewDidLoad() {
self.view.backgroundColor = UIColor.graySpace
}
}