diff options
author | Joey Huang <kamidox@qq.com> | 2015-02-28 19:28:34 +0800 |
---|---|---|
committer | Joey Huang <kamidox@qq.com> | 2015-02-28 19:28:34 +0800 |
commit | b178ac30776698409f6a5e8f3d9f7baf611091b6 (patch) | |
tree | 04e10aaca957157970ad7205920f481bab6f9595 /swift.html.markdown | |
parent | a8592af4e8a5a2381dd55344b6af8de35df673d1 (diff) |
add optional init and enum with associated values
Diffstat (limited to 'swift.html.markdown')
-rw-r--r-- | swift.html.markdown | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/swift.html.markdown b/swift.html.markdown index 0977efc4..ffc57e69 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -3,6 +3,7 @@ language: swift contributors: - ["Grant Timmerman", "http://github.com/grant"] - ["Christopher Bess", "http://github.com/cbess"] + - ["Joey Huang", "http://github.com/kamidox"] filename: learnswift.swift --- @@ -388,6 +389,35 @@ if mySquare === mySquare { println("Yep, it's mySquare") } +// Optional init +class Circle: Shape { + var radius: Int + override func getArea() -> Int { + return 3 * radius * radius + } + + // Place a question mark postfix after `init` is an optional init + // which can return nil + init?(radius: Int) { + self.radius = radius + super.init() + + if radius <= 0 { + return nil + } + } +} + +var myCircle = Circle(radius: 1) +println(myCircle?.getArea()) // Optional(3) +println(myCircle!.getArea()) // 3 +var myEmptyCircle = Circle(radius: -1) +println(myEmptyCircle?.getArea()) // "nil" +if let circle = myEmptyCircle { + // will not execute since myEmptyCircle is nil + println("circle is not nil") +} + // // MARK: Enums @@ -419,6 +449,28 @@ enum BookName: String { } println("Name: \(BookName.John.rawValue)") +// Enum with associated Values +enum Furniture { + // Associate with Int + case Desk(height: Int) + // Associate with String and Int + case Chair(String, Int) + + func description() -> String { + switch self { + case .Desk(let height): + return "Desk with \(height) cm" + case .Chair(let brand, let height): + return "Chair of \(brand) with \(height) cm" + } + } +} + +var desk: Furniture = .Desk(height: 80) +println(desk.description()) // "Desk with 80 cm" +var chair = Furniture.Chair("Foo", 40) +println(chair.description()) // "Chair of Foo with 40 cm" + // // MARK: Protocols |