Last active
October 16, 2019 12:03
-
-
Save PetreVane/dab5befa3993ff38fc1dae25cbe4259c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Stored & computed properties example | |
struct Person { | |
// strored properties | |
var firstName: String | |
var lastName: String | |
// computed property | |
var fullName: String { | |
// getter | |
get { | |
return " \(firstName) \(lastName)" | |
} | |
// setter | |
set (newFullName) { | |
// split the names with an empty space | |
let newFullNameSubstring = newFullName.split(separator: " ") | |
// make sure there are at least 2 names | |
guard newFullNameSubstring.count >= 2 else {print("New name has to contain 2 names"); return } | |
// map new value as string | |
let nameStrings = newFullNameSubstring.map(String.init) | |
// assign the new values to stored property, so the getter will have the new values | |
firstName = nameStrings.first! | |
lastName = nameStrings.last! | |
} | |
} | |
} | |
var person = Person(firstName: "Pete", lastName: "Waveee") | |
person.fullName // returns the values used when instantiating the object | |
person.fullName = "Peter 34444" // assigns new values ( settable computed property) | |
person.fullName // returns the new value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment