简体   繁体   中英

Generics not working with implicitly unwrapped optional

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!

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM