如何创建一个数组或字典,其值只能是String,Int和Boolean?

Tas*_*een 11 arrays dictionary swift

我需要创建一个数组,其值只能是String,Int或boolean.如果我尝试添加Double或任何其他值类型,Swift编译器应该抱怨.

Nan*_*gin 17

protocol Elem {} 
extension Int: Elem {}  
extension String: Elem {} 
extension Bool: Elem {} 
let arr = [Elem]()
Run Code Online (Sandbox Code Playgroud)


vad*_*ian 8

你可以通过声明一个伪协议来做到这一点

protocol SpecialType {}
Run Code Online (Sandbox Code Playgroud)

并让所请求的类型符合该协议

extension String : SpecialType{}
extension Int : SpecialType{}
extension Bool : SpecialType{}
Run Code Online (Sandbox Code Playgroud)

现在,如果您尝试添加Double,编译器会抱怨

let specialDict : [String:SpecialType] = ["1" : "Hello", "2": true, "3": 2.0]
// value of type 'Double' does not conform to expected dictionary value type 'SpecialType'
Run Code Online (Sandbox Code Playgroud)