Optional 如何进行隐式 init 调用?
How Optional does an implicit init call?
我想创建一个类似于 Optional
的枚举。为了举例,假设它是 Optional
:
的副本
public enum MyOptional<T>: ExpressibleByNilLiteral {
case some(T)
case none
public init(_ some: T) { self = .some(some) }
public init(nilLiteral: ()) { self = .none }
}
然后我有一个函数和一个函数调用:
func myFunc(stringParam: MyOptional<String>, intParam: MyOptional<Int>) { ... }
...
obj.myFunc(stringParam: .some("test"), intParam: .none)
但是,我希望能够仅使用文字来调用此函数,Optional
几乎就是这样做的:
obj.myFunc(stringParam: "test", intParam: nil)
但是我得到编译错误 Cannot convert value of type 'String' to expected argument type 'MyOptional<String>'
。同时将 nil
作为第二个参数工作得很好。
我试图使 MyOptional
符合 ExpressibleByStringLiteral
,但看起来这不是可行的方法 - 我无法用不同的文字表达相同的类型。
Optional
是怎么做到的?
更新:
好的,所以符合 ExpressibleBy*Some*Literal
对 Some 类型有好处:
extension MyOptional: ExpressibleByIntegerLiteral where T == Int {
public init(integerLiteral value: Int) { self = .some(value) }
}
extension MuOptional: ExpressibleByStringLiteral, ExpressibleByExtendedGraphemeClusterLiteral, ExpressibleByUnicodeScalarLiteral where T == String {
public typealias ExtendedGraphemeClusterLiteralType = String
public typealias UnicodeScalarLiteralType = String
public init(stringLiteral value: String) { self = .some(value) }
}
...
obj.myFunc(stringParam: "test", intParam: nil) // <- now this works
但当然对其他人无效类:
func myFunc(userParam: MyOptional<User>) { ... }
obj.myFunc(userParam: User(name: "username")) // <- this thing doesn't work :(
非常简单 - Optional
有编译器支持。无法使用自定义代码复制它。
我想创建一个类似于 Optional
的枚举。为了举例,假设它是 Optional
:
public enum MyOptional<T>: ExpressibleByNilLiteral {
case some(T)
case none
public init(_ some: T) { self = .some(some) }
public init(nilLiteral: ()) { self = .none }
}
然后我有一个函数和一个函数调用:
func myFunc(stringParam: MyOptional<String>, intParam: MyOptional<Int>) { ... }
...
obj.myFunc(stringParam: .some("test"), intParam: .none)
但是,我希望能够仅使用文字来调用此函数,Optional
几乎就是这样做的:
obj.myFunc(stringParam: "test", intParam: nil)
但是我得到编译错误 Cannot convert value of type 'String' to expected argument type 'MyOptional<String>'
。同时将 nil
作为第二个参数工作得很好。
我试图使 MyOptional
符合 ExpressibleByStringLiteral
,但看起来这不是可行的方法 - 我无法用不同的文字表达相同的类型。
Optional
是怎么做到的?
更新:
好的,所以符合 ExpressibleBy*Some*Literal
对 Some 类型有好处:
extension MyOptional: ExpressibleByIntegerLiteral where T == Int {
public init(integerLiteral value: Int) { self = .some(value) }
}
extension MuOptional: ExpressibleByStringLiteral, ExpressibleByExtendedGraphemeClusterLiteral, ExpressibleByUnicodeScalarLiteral where T == String {
public typealias ExtendedGraphemeClusterLiteralType = String
public typealias UnicodeScalarLiteralType = String
public init(stringLiteral value: String) { self = .some(value) }
}
...
obj.myFunc(stringParam: "test", intParam: nil) // <- now this works
但当然对其他人无效类:
func myFunc(userParam: MyOptional<User>) { ... }
obj.myFunc(userParam: User(name: "username")) // <- this thing doesn't work :(
非常简单 - Optional
有编译器支持。无法使用自定义代码复制它。