SLN SLN - 6 months ago 10
Swift Question

Problems with the elements creating of the array of structure type

I've created a Structure type named

Location
as

struct Location {
var XCoor: Int
var YCoor: Int
}


I want to create a array of type
Location
I named it as
places


var places : Array<Location>


Quesiont: How to create the element for the Array?

Two of my wrong guesses

places[0](Xcoor: 10, YCoor: 12)// error: cannot call value of non-function type 'Location'


places[0].XCoor = 10
places[0].YCoor = 12 //error: constant 'places' passed by reference before being initialized

Answer

First of all you may want to use constants (instead of variables) and lowercase names inside Location.

struct Location {
    let x: Int
    let y: Int
}

Next this is how you create a mutable array of Locations(s)

var places = [Location]()

And this is how you add a location to places

places.append(Location(x: 1, y: 3))
Comments