| Start |
|---|
| Property, in a protocol extension, achieved using associated object. In Swift, protocol extensions cannot have true properties. However, in practice you can use the "associated object" technique. The result is almost exactly like a "real" property. Here is the exact technique for adding an "associated object" to a protocol extension: Fundamentally, you use the objective-c "objc_getAssociatedObject" and _set calls. The basic calls are: Here's a full example. The two critical points are: So, for an example property "p": In any conforming class, you have now "added" the property "p": You can use "p" just as you would use any ordinary property in the conforming class. Example: Note. You MUST initialize the pseudo-property. Xcode will not enforce you initializing "p" in the conforming class. It is essential that you initialize "p", perhaps in viewDidLoad of the confirming class. It is worth remembering that p is actually just a computed property. p is actually just two functions, with syntactic sugar. There is no p "variable" anywhere: the compiler does not "assign some memory for p" in any sense. For this reason, it is meaningless to expect Xcode to enforce "initializing p". Indeed, to speak more accurately, you must remember to "use p for the first time, as if you were initializing it". (Again, that would very likely be in your viewDidLoad code.) Regarding the getter as such. Note that it will crash if the getter is called before a value for "p" is set. To avoid that, consider code such as: To repeat. Xcode will not enforce you initializing p in the conforming class. It is essential that you initialize p, say in viewDidLoad of the conforming class. Making the code simpler... You may wish to use these two global functions: Note that they do nothing, whatsoever, other than save typing and make the code more readable. (They are essentially macros or inline functions.) Your code then becomes: (In the example at _aoGet, P is initalizable: instead of P() you could use "", 0, or any default value.) |
Read Article
https://develop.horje.com/learn/1434/reference