Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an Array or Dictionary whose values can only be String, Int and Boolean? [duplicate]

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.

like image 795
Taseen Avatar asked Mar 28 '17 06:03

Taseen


People also ask

Which one creates a dictionary with a key type of integer and value of string?

The Key type of the dictionary is Int , and the Value type of the dictionary is String . To create a dictionary with no key-value pairs, use an empty dictionary literal ( [:] ). Any type that conforms to the Hashable protocol can be used as a dictionary's Key type, including all of Swift's basic types.

What is the type of string array and dictionary in Swift?

Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.

How do you create an array of strings in Swift?

Swift makes it easy to create arrays in your code using an array literal: simply surround a comma-separated list of values with square brackets. Without any other information, Swift creates an array that includes the specified values, automatically inferring the array's Element type.

What is the difference between an array and a set Swift?

Difference between an Array and Set in SwiftArray is faster than set in terms of initialization. Set is slower than an array in terms of initialization because it uses a hash process. The array allows storing duplicate elements in it. Set doesn't allow you to store duplicate elements in it.


2 Answers

protocol Elem {} 
extension Int: Elem {}  
extension String: Elem {} 
extension Bool: Elem {} 
let arr = [Elem]()
like image 142
Nandin Borjigin Avatar answered Sep 28 '22 16:09

Nandin Borjigin


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'
like image 33
vadian Avatar answered Sep 28 '22 17:09

vadian