struct array initialization in Swift struct array initialization in Swift swift swift

struct array initialization in Swift


One option might be for you to instead use an Array of Tuples:

var data = Array<(company: String, city: String, state: String, latitude: Float, longitude: Float)>()

Now the individual elements of your Tuple are labeled and can be accessed by those labels, even if they weren't used to create an instance of the Tuple in the first place:

var datumOne = ("MyCompany", "MyCity", "MyState", 40.2, 139.45)data += datumOneprintln(data[0].state)      // MyStatedata = [    ( "Joes Crab Shack", "Miami", "FL", 30.316599, -119.050254),    ( "Jims Crab Shack", "Los Angeles", "CA", 35.316599, -112.050254)]println(data[1].company)    // Jims Crab Shack

However, doing this doesn't give you the Type goodness that you get out of a Structure... in Swift all Structures automatically get what's called a "member-wise initializer", which requires that you initialize them like so, using the member names as argument labels (and in the order in which they are declared in the Structure):

var myDatum = MyData(company: "The Company", city: "The City", state: "The State", latitude: 90.2, longitude: 140.44)

You are able to define your own init() method for your Structure, however, if you'd like to use an initializer that is better suited to your purpose.

So, to give yourself an Array of Structures using the default member-wise initializer you'd simply do:

let allMyData = [    MyData(company: "Jims Crab Shack", city: "Los Angeles", state: "CA", latitude: 35.316599, longitude: -112.050254),    MyData(company: "Joes Crab Shack", city: "Miami", state: "FL", latitude: 30.316599, longitude: -119.050254)]


Like this (note I changed the name of your struct to match Swift style guidelines):

struct MyData {  var company = String()  var city    = String()  var state   = String()  var latitude:  Float  var longitude: Float}let data = [  MyData(company: "Joes Crab Shack", city: "Miami", state: "FL", latitude: 30.316599, longitude: -119.050254),  MyData(company: "Jims Crab Shack", city: "Los Angeles", state: "CA", latitude: 35.316599, longitude: -112.050254)]


j.s.com you wrote:

var myStruct: TheStruct = TheStruct

but I've tried it and doesn't work.For me works fine this one:

var myStruct :[TheStruct] = []