Reputation: 32273
I created an extension of UIView to be able to create and add a subview in one line:
extension UIView {
func createAndAddSubview<T:UIView>() -> T {
let view = T()
self.addSubview(view)
return view
}
}
This works with normal declarations:
let myLabel:UILabel = view.createAndAddSubview()
var myImageView:UIImageView = view.createAndAddSubview()
But with implicitly wrapped optionals I get a compiler error. I think it's because the optional prevents the compiler from determining the correct type.
'UIView' is not convertible to 'UILabel'
class MyController {
var myLabel:UIlabel!
func foo() {
myLabel = view.createAndAddSubview()
}
}
Of course I can get it to work like this
let myLabel:UILabel = view.createAndAddSubview()
self.myLabel = myLabel
But this isn't one line anymore... how can I improve it?
Thanks!
Upvotes: 0
Views: 165
Reputation: 27335
I guess compiler cannot infer the type as its ImplicitlyUnwrappedOptional
. Try:
self.myLabel = .Some(self.view.createAndAddSubview())
or
extension UIView {
func createAndAddSubview<T:UIView>() -> T? {
let view = T()
self.addSubview(view)
return view
}
}
Upvotes: 1