21

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.

2
  • Keep in mind that semicolons doesn't exist in Swift Commented Jan 2, 2015 at 12:18
  • 1
    Well, you can use semicolons if you want to, but they aren't standard. Commented Feb 6, 2015 at 15:42

6 Answers 6

23

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)
]
Sign up to request clarification or add additional context in comments.

1 Comment

Array of Tuples is a bad idea. To quote from the documentation: NOTE Tuples are useful for temporary groups of related values. They are not suited to the creation of complex data structures. If your data structure is likely to persist beyond a temporary scope, model it as a class or structure, rather than as a tuple. For more information, see Classes and Structures.
19

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)
]

3 Comments

one question: why do you declare String as new objects?
@IanBell because I was copy/pasting code from the question and they chose to do that. Also note that setting a default value of an empty string means you never have to deal with optionals.
Ah, ok! I thought there was another reason, thanks! :-)
7
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

Comments

6

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

Comments

2

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
}

1 Comment

the name of the struct properties should start with a lowercase letter
1
struct _data {

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

}

//To initialize
var MyData = [_data()];
//To access
MyData[index].company or .city etc..
//To Add new element
MyData.append(_data(company: theCompany, city: theCity, state: theState, latitude: theLatitude, longitude: theLongitude));
//To count
MyData.count

Cheers

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.