【发布时间】:2020-04-28 12:31:40
【问题描述】:
有protocols用字面量实现初始化。
示例:通过使用ExpressibleByStringLiteral,我们可以执行以下操作:
struct MyString: ExpressibleByStringLiteral {
let value: String
init(stringLiteral value: String) {
self.value = value
}
}
let str: MyString = "Hello World!" // It's the same as: `MyString(stringLiteral: "Hello World!")`
str.value // "Hello World!"
此外,通过使用ExpressibleByIntegerLiteral,我们可以执行以下操作:
struct MyInt: ExpressibleByIntegerLiteral {
let value: Int
init(integerLiteral value: Int) {
self.value = value
}
}
let int: MyInt = 101 // It's the same as: `MyInt(integerLiteral: 101)`
int.value // 101
我的问题是:
我们如何为具有泛型类型的结构应用相同的逻辑?考虑我有以下结构:
struct MyCustom<T> {
let value: T
}
我想做的是:
let custom1: MyCustom = "Hello World!"
custom1.value // "Hello World!"
// OR (since its generic)
let custom2: MyCustom = 101
custom1.value // 101
在这种情况下要遵循什么适当的协议?
【问题讨论】:
标签: swift initialization swift-protocols