Skip to content

Instantly share code, notes, and snippets.

@hanawat
Created January 19, 2016 17:03
Show Gist options
  • Save hanawat/c4caef0a3df3ec30b16c to your computer and use it in GitHub Desktop.
Save hanawat/c4caef0a3df3ec30b16c to your computer and use it in GitHub Desktop.
Using Type property, a class, enum, and structure can make Value in itself.
struct Greet {
let string: String
static let words = ["Nice", "to", "meet", "see", "you."] // Type property
static var first = true // Type property
init(name: String) {
// Refer type property and method from initializer
string = Greet.first ? Greet.first(name) : Greet.usual()
}
// Type method
static func first(name: String) -> String {
let greet = words.filter { $0 != "see" }
return "I'm \(name). " + greet.joinWithSeparator(" ")
}
// Type method
static func usual() -> String {
let greet = words.filter { $0 != "meet" }
return greet.joinWithSeparator(" ")
}
}
let firstGreet = Greet(name: "Keith")
print(firstGreet.string) // I'm Keith. Nice to meet you.
Greet.first = false
let secondGreet = Greet(name: "Keith")
print(secondGreet.string) // Nice to see you.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment