Created
January 19, 2016 17:03
-
-
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.
This file contains 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
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