12

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.

Hamish
  • 78,605
  • 19
  • 187
  • 280
Taseen
  • 1,213
  • 1
  • 11
  • 18

2 Answers2

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
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
  • ok got it... thanks :) – Bhavin Bhadani Mar 28 '17 at 08:11