简体   繁体   中英

Conforming a generic type to a protocol in a Swift extension

I'm trying to make a Swift generic type conform to a protocol in an extension . This is the type:

enum Maybe<T>{
    case Nothing
    case Something(T)

    init(){
        self = .Nothing
    }

    init(_ something: T){
        self = .Something(something)
    }

}

The protocol I want it to conform is NilLiteralConvertible

If I try in an extension, I get a bunch of crazy errors:

extension Maybe<T>: NilLiteralConvertible{

}

I can only implement it if I declare in main definition of Maybe<T> . What the heck???

enum Maybe<T>: NilLiteralConvertible{
    case Nothing
    case Something(T)

    init(){
        self = .Nothing
    }

    init(_ something: T){
        self = .Something(something)
    }


    // NilLiteralConvertible
    static func convertFromNilLiteral() -> Maybe<T> {

        return Maybe<T>()

    }

}

The correct syntax for an extension of a class/struct/enum using generics is:

extension Maybe : NilLiteralConvertible {    
    static func convertFromNilLiteral() -> Maybe {
        return .Nothing
    }
}

so you don't have to specify the generic type T , it's already declared in the main definition. If you specify it, it's like you are defining a new generic type

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