Syntax explanation: square brackets in Swift

[Treasure] is just a syntax sugar for Array<Treasure>.

The same way [String:Treasure] is just a syntax sugar for Dictionary<String,Treasure>.

[] is just an empty array of the type you defined. The same way [:] is an empty dictionary.

When it comes to Swift and square brackets, the rules are simple. They are used only in two situations:

1) working with Array and Dictionary types:

let vectors : [[Int]] = [[1,2,3],[4,5,6]]
let birthBook : [Int:[String]] = [1987:["John","William"], 1990: ["Mary"]]

2) for subscripting objects that support subscripting:

class RouteMapper {

    private var routeMap : [String:String] = [:]

    subscript(endpoint: String) -> String {
        get {
            if let route = routeMap[endpoint] {
                return route
            }
            return "/"
        }
        set(newValue) {
            routeMap[endpoint] = newValue
        }
    }
}

let routeMapper = RouteMapper()
routeMapper["users"] = "/v1/confirmed/users"
let url = routeMapper["admins"]

Since [ and ] are not allowed in custom operators, these are the only usages for now.


Ok, this is the meaning of

var treasures: [Treasure] = []
  • var: you are declaring a variable
  • treasures: the name of your variable
  • [Treasure]: the type of your variable, in this case the type is Array of Treasure, the compiler will allow you to insert only object of type Treasure in your Array
  • []: the actual object (Array) referenced by your variable, in this case an empty Array.

E.g. if you want the Array to hold 2 elements you can write

var treasures: [Treasure] = [Treasure(), Treasure()]

Hope this helps.

Update: My example can also be written this way

var treasures = [Treasure(), Treasure()]

Infact thanks to the Type Inference the compiler can deduce the type of the variable treasures looking at the type of the assigned value.

Tags:

Arrays

Ios

Swift