2016-05-14 81 views
0

我創建了一個名爲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 
+1

如果您需要澄清語法來處理數組,我肯定會推薦[Apple的真正簡潔明瞭的指南](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes。 html#// apple_ref/doc/uid/TP40014097-CH8-ID107)(以及Swift基礎的其餘部分)。 – Hamish

+0

@ originaluser2感謝您的文檔 – SLN

回答

1

所有你可能需要使用常量(而不是變量)和小寫名稱中的第一個Location

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

接下來你這是怎麼創造的Locations(S)

var places = [Location]() 

一個可變的數組,你這是怎麼添加位置的地方

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

感謝您的解釋和幫助 – SLN

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

places.append(firstLocation) 
+0

感謝您的演示代碼 – SLN

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 
+0

@ luk2320非常感謝您的詳細解釋和代碼演示 – SLN