Silent Edits Silent Edits - 3 months ago 8
Swift Question

How to use NSObject properties

So I have an

NSObject
called
Account
with some variables in it. I've added getter and setter methods in the class, but when I try to set the values and call get them I get nil.

import UIKit


class Account: NSObject {

var firstName: String = ""
var lastName: String = ""


//setters
func setNameFirst(newName: String){
firstName = newName
}

func setNameLast(newName: String){
lastName = newName
}

//getters
func getFirstName() -> String{
return firstName
}

func getLastName() -> String{
return lastName
}

}


In another view controller I try to set and print one of the variables.

import UIKit

var test: Account?

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
test?.setNameFirst("John")
print(test?.getFirstName())
}

}


but I get
nil
when it prints.

Answer

You declared test as an optional Account --- that's what Account? is.

Given that you never initialized it to anything it will remain nil and prints nil.

To correct this you will need to add (as vacawama said in the comments):

test = Account() // test no longer nil

Now test will be an instance of Account instead of nil.

Additional example, in a playground:

let test : Account?
print(test) // won't run

but

let test : Account?
test = Account()
print(test) // prints an instance of Account

Also, your getters and setters are redundant.

Doing this:

let test = Account()
test.firstName = "First"
print(test.firstName) // prints "First\n"

is the same as:

let test = Account()
test.setNameFirst("First")
print(test.getFirstName()) // prints "First\n"