元素创建结构类型

时间:2016-05-14 18:42:17

标签: arrays swift struct

我创建了一个名为Location结构类型为

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

我想创建一个Location类型的数组,我将其命名为places

var places : Array<Location>

Quesiont:如何为数组创建元素?

我猜错了两个错误

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

3 个答案:

答案 0 :(得分:1)

let firstLocation = Location(XCoor: 10, Ycoor: 10) 

places.append(firstLocation)

答案 1 :(得分:1)

语法如下:

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

var places : [Location] // a bit of syntactic sugar, dropping the Array<...>
places = [] // actually create the empty array

var places2 = [Location]() // alternate, shorter, more swifty version of the two lines before

places.append(Location(XCoor: 10, YCoor: 12)) // create an instance of the struct append it to the array

答案 2 :(得分:1)

首先,您可能希望在malloc中使用常量(而不是变量)和小写名称。

Location

接下来,您将创建一个struct Location { let x: Int let y: Int } (s)

的可变数组
Locations

这就是你向地方添加位置的方式

var places = [Location]()