有没有办法在 Swift 中将泛型限制为一种或另一种类型?



有没有办法向泛型添加多个可选约束?我希望我的泛型是字符串或布尔值。像这样:

func myFunction<T>(_ dict: [String: T]) where T == String || T == Bool {
// Do stuff with dict
}

你可以创建一个协议,让 String 和 Bool 符合它:

protocol StringOrBool { }
extension Bool: StringOrBool {}
extension String: StringOrBool {}

func myFunction<T: StringOrBool>(_ dict: [String: T])  {
print(dict)
}
myFunction(["a": true])
myFunction(["b": "test"])
myFunction(["b": 1]) // error: MyPlayground Xcode 11.playground:706:1: error: global function 'myFunction' requires that 'Int' conform to 'StringOrBool'

不能将泛型限制为单个类型:

// error: Same-type requirement makes generic parameter 'T' non-generic
func myFunction<T>(_ dict: [String: T]) where T == String {
}

您可能希望对类型进行一些函数重载:

func myFunction(_ dict: [String: String]) {
print("String")
}
func myFunction(_ dict: [String: Bool]) {
print("Bool")
}
let strings = ["a": "b"]
let bools = ["a": false]
myFunction(strings) // print String
myFunction(bools) // print Bool

最新更新