Silent Edits Silent Edits - 2 months ago 6x
Swift Question

How to use NSObject properties

So I have an

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 = ""

func setNameFirst(newName: String){
firstName = newName

func setNameLast(newName: String){
lastName = newName

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() {


but I get
when it prints.


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


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()
print(test.getFirstName()) // prints "First\n"