Hi Everyone,
I am trying to reduce boilerplate code when writing custom UIViewController subclasses which talk to a custom UIView subclass, like in a traditional MVC design, and I would like to use the following pattern in many places in my apps:
protocol ViewTypeable {
associatedtype ViewType: UIView
var view: ViewType { get }
}
extension ViewTypeable where Self: UIViewController {
var view: ViewType { return self.view as! ViewType }
}
I'm not sure how others would call this, but I call it property overloading, because it's a bit similar to how we can overload a function by changing the type of a parameter.
Here is a simple exemple of how I use it:
class View1: UIView {
var text1 = ""
}
class ViewController1: UIViewController, ViewTypeable {
typealias ViewType = View1
override func loadView() {
self.view = View1()
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.text1 = "some text"
}
}
In the above example, when I start typing self.view
in XCode, autocompletion shows 2 view
properties, one of type UIView
and the other of type View1
.
I don't really understand what is happening under the hood, so I thought I should ask the good people at swift forums if this technique is considered safe, or if it is likely to break in a future version of Swift, particularly this line:
var view: ViewType { return self.view as! ViewType }
Thanks.