Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions codes/ExtensionStoredProperty.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Did you never asked how to add stored properties to extensions in Swift? ;)
// One of the benfits of Objective C and key-value coding feature code
// is still valid in Swift is you can we could add stored values to an object at runtime.
// Say welcome to associated object in Swift.

import Foundation

class MyClass {
}

// We declared the type of key as Void?, which means a pointer to anything
private var key: Void?

extension MyClass {
var title: String? {
get {
// Then & operator is used to get key address and send
// into the method as UnsafePointer<Void> parameter.
// associated object API get method.
return objc_getAssociatedObject(self, &key) as? String
}
set {
// associated object API set method.
objc_setAssociatedObject(self, &key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}

// Test function
func printTitle(input: MyClass) {
if let title = input.title {
print("Title: \(title)")
} else {
print("not set")
}
}

let myClassObject = MyClass()
printTitle(input: myClassObject)

myClassObject.title = "Swift Daily Tips 1"
printTitle(input: myClassObject)

myClassObject.title = "Swift Daily Tips 2"
printTitle(input: myClassObject)
Binary file added screenshots/ExtensionStoredProperty.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.