Can't append structure to array property

时间:2015-07-28 22:10:52

标签: ios swift struct

When I add non-empty location to locations property of User, this property remains nil.

public struct User: Printable {
    var name: String
    var locations: [LocationData] = []

    public var description: String {
        return "User: \(name), locations: \(locations)"
    }
}

public struct LocationData: Printable {
    var unixtime: NSTimeInterval
    var latitude: CLLocationDegrees
    var longitude: CLLocationDegrees

    var date: NSDate{
        return NSDate(timeIntervalSince1970: unixtime)
    }

    public var description: String {
        return "LocationData: date: \(date), latitude: \(latitude), longitude: \(longitude)"
    }
}

This is how I add locations to user:

    for userText in usersArray{
        let userFieldsArray = userText.componentsSeparatedByString(("|"))

        let username = userFieldsArray[0]
        var user = users.filter{$0.name == username}.first

        if user == nil{

            user = User(name: username, locations: [])
            users.append(user!)

        }

        let unixtime = (userFieldsArray[1] as NSString).doubleValue
        let latitude = (userFieldsArray[2] as NSString).doubleValue
        let longitude = (userFieldsArray[3] as NSString).doubleValue

        let location = LocationData(unixtime: unixtime, latitude: latitude, longitude: longitude)
        user?.locations.append(location)
    }

1 个答案:

答案 0 :(得分:0)

This is the usual confusion about value types versus reference types, coming from a Java or C++ background. When you assign the user's contents to the local variable user, then mutate that variable at the bottom of your sample, you're only modifying the local copy. Change User over to a class and all will work.

Stylistically, if you're using a force-unwrap earlier in the code, you should also use a force-unwrap at the bottom, because you wouldn't want that to fail silently.

Alternatively, keep it a struct but don't put user into users until it's fully mutated.