I have a requirement where I need to create an array whose values can only be either String, Int or boolean. Swift compiler should complain if I tried to add Double or any other value type.
Asked
Active
Viewed 698 times
2 Answers
20
protocol Elem {}
extension Int: Elem {}
extension String: Elem {}
extension Bool: Elem {}
let arr = [Elem]()

Ahmad F
- 30,560
- 17
- 97
- 143

Nandin Borjigin
- 2,094
- 1
- 16
- 37
-
Thanks. Since you were first, I have to accept your answer – Taseen Mar 28 '17 at 06:48
-
Referring to testing the code snippet, I did that and it works as it should, please accept my edit :) – Ahmad F Mar 28 '17 at 06:53
9
You can do it by declaring a dummy protocol
protocol SpecialType {}
and let conform the requested types to that protocol
extension String : SpecialType{}
extension Int : SpecialType{}
extension Bool : SpecialType{}
Now the compiler complains if you try to add a 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'

vadian
- 274,689
- 30
- 353
- 361
-
can we make extension of `[String:Any]` or `[[String:Any]]` with SpecialType?? – Bhavin Bhadani Mar 28 '17 at 07:13
-
This is not necessary. Just replace `Any` with `SpecialType`. The collections `Array` and `Dictionary` will consider it correctly. – vadian Mar 28 '17 at 07:53
-
no I mean what if I want to check that data is of type array or dictionary .. is this same thing we can use with array or dictionary? – Bhavin Bhadani Mar 28 '17 at 07:54
-
I don't understand. The collection types are generics. The associated types are checked anyway. – vadian Mar 28 '17 at 08:05
-
@EICaptainv2.0 , It's yes and no. Swift simply doesn't support that kind of extension for current version, but there's a proposal to support it. Once supported the syntax should be `extension Array: SpecialType where Element == String` (this should give compiler error for now) – Nandin Borjigin Mar 28 '17 at 08:07
-