cyclingIsBetter
cyclingIsBetter

Reputation: 17591

iOS: create an object class with Swift

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"

Upvotes: 18

Views: 88286

Answers (5)

Mithra Singam
Mithra Singam

Reputation: 2091

Just like any other object oriented programming language, and object should be initialized before accessing it.
Like:

var city:City

This is just reference of the object. So, actual memory is not created here. You need to create actual object for City Class.

Fix it by adding following statement:

city = City()

Upvotes: 16

Antonio
Antonio

Reputation: 72780

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
    

Upvotes: 33

Dhruv Ramani
Dhruv Ramani

Reputation: 2643

You have to call the init method. So you would do it like this :

var city:City=City() //Calls init and creates an instance
city.name="foo"

If you don't define an init method(it's always a good practice that you do), the default init method is called.

Upvotes: 1

Zell B.
Zell B.

Reputation: 10296

You are getting error because you are not initializing your city variable instead you just implicitly unwrap it without initializing at any stage. To initialize it you must use the following code

var city:City = City()

Upvotes: 4

Greg
Greg

Reputation: 25459

You haven't initialised the city variable and when you trying to use it it crash.

initialise it first before you use it:

city = City()
city.name = "London"

Upvotes: 6

Related Questions