iOS: create an object class with Swift

cyclingIsBetter picture cyclingIsBetter · Feb 9, 2015 · Viewed 75.1k times · Source

I created this class for my object City

class City: NSObject {

    var _name:String = ""
    var name:String {
        get {
            return _name
        }
        set (newVal) {
            _name = newVal
        }
    }
}

then when I create my object I do:

var city:City!

city.name = "London" //crash here

println("name city is\(city.name)");

it crash when I set the name with message "fatal error: unexpectedly found nil while unwrapping an Optional value"

Answer

Antonio picture Antonio · Feb 9, 2015

This is not actually an answer (see other answers for a solution, such as @Greg's and @zelib's), but an attempt to fix some mistakes I see in your code

  1. No need to create computed + stored property (unless you have a reason for that):

    class City: NSObject {
        var name: String = ""
    }
    
  2. If you inherit from NSObject, you automatically lose all swift features - avoid it (unless you have a reason for that)

    class City {
        var name: String = ""
    }
    
  3. You are using an empty string as absence of value - swift provides optionals for that

    class City {
        var name: String?
    }
    
  4. Alternative to 3., a city without a name wouldn't make much sense, so you probably want each instance to have a name. Use non optional property and an initializer:

    class City {
        var name: String
        init(name: String) {
            self.name = name
        }
    }
    
  5. Avoid implicitly unwrapped optionals (unless you have a reason for that):

    var city: City