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.
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.
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.
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.
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.
protocol Elem {}
extension Int: Elem {}
extension String: Elem {}
extension Bool: Elem {}
let arr = [Elem]()
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With