John John - 9 days ago 6
Swift Question

What arguments can I pass into array or set or dictionary in swift?

For example:

var example1 = [anyType](what arguments to pass)


var example2 = Set<anyType>(what arguments to pass)


var example3 = [anyType: anyType](what arguments to pass)


Can you give me examples by an explanation ?

Answer

In a Swift playground, type Array.init. Xcode will show you all the different forms of the Array.init method. (You may need to press control-space if you don't have the “Suggest completions while typing” preference turned on.)

It looks like this:

Array.init completions

So we can see that you can initialize an array with any Sequence (another array, a range, a set, etc.). Example:

let ex1 = [Int](0 ..< 5)

Or you can use an array literal:

let ex2 = [Int]([2, 3, 5])

Or you can give an element and the number of copies of the element you want in the array:

let ex3 = [Int](repeating: 9, count: 3)

In all of these cases, there's no particular reason to say [Int]. Here's the natural way to write these examples:

let ex4 = Array(0 ..< 5)
let ex5 = [2, 3, 5]
let ex6 = Array(repeating: 9, count: 3)

The only time we'd normally write [Int] on the right side of an = is to create an empty array:

let ex7 = [Int]()

You can use Xcode completion to see the possible arguments to Set.init and Dictionary.init.