Thursday, 15 April 2010

struct array initialization in Swift -



struct array initialization in Swift -

continuing play around in swift , trying convert c world , have been stuck trying various syntax. have fixed info want initialize construction array. here's how wold in c can't figure out in swift rather maintain guessing i'll inquire know more. here's c code.

#include <stdio.h> typedef struct my_data { const char *company; const char *city; const char *state; float latitude; float longitude; } my_data; int main() { my_data data[2]={ { "joes crab shack", "miami", "fl", 30.316599, -119.050254}, { "jims crab shack", "los angeles", "ca", 35.316599, -112.050254} }; }

in swift can create similar struct...

struct my_data { var company = string(); var city = string(); var state = string(); var latitude:float; var longitude:float; }

now stuck in how declare , initialize fixed info doing in c. guessing simple , getting syntax right has baffled me. i'd maintain initialization style in similar format c since can extract , format info file.

one alternative might instead utilize array of tuples:

var info = array<(company: string, city: string, state: string, latitude: float, longitude: float)>()

now individual elements of tuple labeled , can accessed labels, if weren't used create instance of tuple in first place:

var datumone = ("mycompany", "mycity", "mystate", 40.2, 139.45) info += datumone println(data[0].state) // mystate info = [ ( "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 doesn't give type goodness out of structure... in swift structures automatically what's called "member-wise initializer", requires initialize them so, using fellow member names argument labels (and in order in declared in structure):

var mydatum = mydata(company: "the company", city: "the city", state: "the state", latitude: 90.2, longitude: 140.44)

you able define own init() method structure, however, if you'd utilize initializer improve suited purpose.

so, give array of structures using default member-wise initializer you'd 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) ]

swift

No comments:

Post a Comment