Skip to content

Instantly share code, notes, and snippets.

@PetreVane
Last active October 16, 2019 12:03
Show Gist options
  • Save PetreVane/dab5befa3993ff38fc1dae25cbe4259c to your computer and use it in GitHub Desktop.
Save PetreVane/dab5befa3993ff38fc1dae25cbe4259c to your computer and use it in GitHub Desktop.
// 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