自定义可表达协议在 Swift 中实现隐式构造

问题描述 投票:0回答:1

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'
swift swift4
1个回答
0
投票

使用自定义运算符:

postfix operator |

postfix func |(context: Foo) -> Bar {
   Bar(context)
}

let foo = Foo()
let aMyType: Bar = foo|

//Even with generics
postfix func |<C, T>(context: C) -> T

查看示例此处

/// Obtain
///
/// let object: T = context|
///

postfix func |<C, T: Obtain>(context: C) -> T {
    Wand.attach(to: context).obtain()
}

https://github.com/El-Machine/Wand

© www.soinside.com 2019 - 2024. All rights reserved.