Robert Mellor
Robert Mellor

Reputation: 73

Adding a string from UserDefaults into an already made array Swift 3

I've got my users first name and I've set it in a UserDefault and I call it like so..

let firstName = UserDefaults.standard.object(forKey: "firstName")

Then I have an array of strings and I would like to add the users first name into that..

var arrayOfTitle = ["HEY", "FIND EVENTS CLOSE TO YOU", "BOOK"]

I've tried what I would think it should look like which is

var arrayOfTitle = ["HEY \(firstName)", "FIND EVENTS CLOSE TO YOU", "BOOK"]

but that isn't working.

Would anyone be able to push me or demonstrate to get me in the right direction.

Thanks!

Upvotes: 0

Views: 594

Answers (2)

Mobile Dan
Mobile Dan

Reputation: 7114

UserDefaults.string(forKey:)

Use UserDefaults.string(forKey:) instead of UserDefaults.object(forKey:).

let firstName = UserDefaults.standard.string(forKey: "firstName") ?? "YOU"
var arrayOfTitle = ["HEY \(firstName)", "FIND EVENTS CLOSE TO YOU", "BOOK"]

UserDefaults.standard.object(forKey:) returns Any? which you must unwrap and convert to a string. UserDefaults.standard.string(forKey:) converts the result to String? which can simplify your code.

The nil-coalescing operator, ??, unwraps the String? result if it contains a value, or returns the default value "YOU" if the result is nil. Without the ?? operator, if there is not a UserDefault stored for "firstName", it will return nil resulting in "HEY nil".

 

Optional Binding

You can use optional binding with UserDefaults.string(forKey:) if you want to conditionally run code if a value exists or not.

if let firstName = UserDefaults.standard.string(forKey: "firstName") {
    print("\(firstName)")
}

Upvotes: 1

Marc Ibrahim
Marc Ibrahim

Reputation: 309

if let name = UserDefaults.standard.object(forKey: "firstName") as? String{
    arrayOfTitle.append(name)
}

Upvotes: 0

Related Questions