考虑以下:
struct MiniString {
private(set) var value: String
init(_ value: String) {
if value.count < 17 {
self.value = value
} else {
selfDeleteSomehow()
}
}
}
在其他地方,这可以实例化:
var ms: MiniString? = MiniString("This string is too long to be accepted")
print(ms) // prints 'nil'
上下文:我的特定用例是协议中的func声明,它将返回介于0.0和1.0之间的Double
,但不会更高或更低,例如:
protocol DoubleBetweenZeroAndOneProtocol {
func getResult() -> DoubleBetweenZeroAndOne
}
您可以使用可用的初始化程序:
struct MiniString {
var value: String { return value_ }
private let value_: String
init?(_ seedValue: String) {
if seedValue.count < 17 {
value_ = seedValue
} else {
return nil
}
}
}