AFAIK,Swift class可以通过符合的字面值来分配ExpressibleBy*Literal.
例如,类A可以Int像这样分配,这类似于隐式构造C++
class A : ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
required init(integerLiteral value: A.IntegerLiteralType) {
}
}
var a: A = 1
Run Code Online (Sandbox Code Playgroud)
现在,我可以将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'
Run Code Online (Sandbox Code Playgroud)