自定义可识别协议在Swift中实现隐式构造

时间:2017-10-12 03:35:11

标签: swift swift4

AFAIK,Swift class可以通过符合ExpressibleBy*Literal的字面值进行分配。

例如,A类可以像Int这样分配,类似于C++中的隐式构造

class A : ExpressibleByIntegerLiteral {
    typealias IntegerLiteralType = Int

    required init(integerLiteral value: A.IntegerLiteralType) {
    }
}

var a: A = 1

现在,我可以将ExpressibleBy*协议扩展到我的任何自定义类型吗?

protocol ExpressibleByMyTypeLiteral {
    associatedtype MyType

    init(literal value: Self.MyType) 
}

class B {
}

class A : ExpressibleByIntegerLiteral, ExpressibleByMyTypeLiteral {
    //ExpressibleByIntegerLiteral
    typealias IntegerLiteralType = Int

    required init(integerLiteral value: A.IntegerLiteralType) {
    }

    //ExpressibleByMyTypeLiteral
    typealias MyType = B

    required init(literal value: A.MyType) {
    } 
}

var a: A = 1
var aMyType: A = B() //Compiler Error: Cannot convert value of 'B' to specified type 'A'

0 个答案:

没有答案