Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct array initialization in Swift

Tags:

swift

Continuing to play around in Swift and trying to convert something from the C world and have been stuck trying various syntax. I have some fixed data I want to initialize into a structure array. Here's how I wold do it in C but I can't figure it out in Swift so rather than keep guessing I'll ask those that know more. Here's my 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 I can create a similar struct...

struct my_data {
    var company = String();
    var city = String();
    var state = String();
    var latitude:Float;
    var longitude:Float;
}

Now I am stuck in how to declare and initialize the fixed data like I am doing in C. Guessing it is something simple and getting the syntax right has baffled me. I'd like to keep the initialization style in the similar format to C since I can easily extract and format this data from a file.

like image 834
Kokanee Avatar asked Jun 24 '14 03:06

Kokanee


People also ask

How do you initialize a struct in Swift?

In Swift, all structs come with a default initializer. This is called the memberwise initializer. A memberwise initializer assigns each property in the structure to self. This means you do not need to write an implementation for an initializer in your structure.

How do you declare an array in Swift?

We declare an array in Swift by using a list of values surrounded by square brackets. Line 1 shows how to explicitly declare an array of integers. Line 2 accomplishes the same thing as we initialize the array with value [1, 2] and Swift infers from that that it's an array of integers.

How do you define a struct in Swift?

A struct definition is just a blueprint. To use a struct, we need to create an instance of it. For example, struct Person { var name = " " var age = 0 } // create instance of struct var person1 = Person() Here, we have created an instance by writing the name of the structure Person followed by a default initializer ()


5 Answers

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 += datumOne
println(data[0].state)      // MyState

data = [
    ( "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 image 116
fqdn Avatar answered Oct 10 '22 04:10

fqdn


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)
]
like image 30
Abhi Beckert Avatar answered Oct 10 '22 02:10

Abhi Beckert


struct MyData {

    var company = String()
    var city = String()
    var state = String()
    var latitude:Float
    var longitude:Float

}

var dataArray = [MyData]()

var data = MyData(company: "Joes Crab Shack", city: "Miami", state: "FL", latitude: 30.316599, longitude: -119.050254)

// can add the struct like this

dataArray.append(data)

// or like this

dataArray.append(MyData(company: "Jims Crab Shack", city: "Los Angeles", state: "CA", latitude: 35.316599, longitude: -112.050254))

// to get an element

var thisCompany = dataArray[0].company // Joes Crab Shack

// to change an element

dataArray[0].city = "New York"

var thisCity = dataArray[0].city // New York
like image 23
Jeff Tiedemann Avatar answered Oct 10 '22 03:10

Jeff Tiedemann


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] = []

like image 36
FrancescoRetain Avatar answered Oct 10 '22 04:10

FrancescoRetain


Here you get a small example how to handle arrays of struct in Swift:

First the definition of the Structure:

struct TheStruct
{
    var Index: Int = 0
    var Name: String = ""
    var Sample: [String] = [String]()
}
var myStruct: TheStruct = [TheStruct]()

Then appending an element to the structure

func Append1Element()
{
    myStruct.append(TheStruct(Index: 0, Name: "", Sample: []))
}

And changing en existing element:

func ChangeName(theName: String)
{
    myStruct[0].Name: theName
}
like image 36
j.s.com Avatar answered Oct 10 '22 03:10

j.s.com