I make a protocol:
protocol SomeProtocol {
func getData() -> String
}
I make a struct that conforms to it:
struct SomeStruct: SomeProtocol {
func getData() -> String {
return "Hello"
}
}
Now I want every UIViewController
to have a property called source
, so I can do something like…
class MyViewController : UIViewController {
override func viewDidLoad() {
self.title = source.getData()
}
}
To accomplish this, I create a protocol to define the property:
protocol SomeProtocolInjectable {
var source: SomeProtocol! { get set }
}
Now I just need to extend the view controller with this property:
extension UIViewController: SomeProtocolInjectable {
// ???
}
How can I hack together a stored property that will work with a protocol type?
What hasn't worked:
var source: SomeProtocol!
obviously doesn't work because extensions don't have stored properties- I can't use Objective-C associated objects because a protocol isn't an object
- I can't wrap it in a class (this does work for other value types, but not protocols)
Any other suggestions?