iOS: create an object class with Swift
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()
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
No need to create computed + stored property (unless you have a reason for that):
class City: NSObject { var name: String = "" }
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 = "" }
You are using an empty string as absence of value - swift provides optionals for that
class City { var name: String? }
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 } }
Avoid implicitly unwrapped optionals (unless you have a reason for that):
var city: City
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"
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()