diff options
author | Geoff Liu <cangming.liu@gmail.com> | 2015-03-02 19:17:24 -0700 |
---|---|---|
committer | Geoff Liu <cangming.liu@gmail.com> | 2015-03-02 19:17:24 -0700 |
commit | d2d3efead458aa0921862a3a5f413f47cabf432d (patch) | |
tree | 16110234773b3e9215379abfa4961fe252b47b45 /swift.html.markdown | |
parent | bf2917e4ab4b24378c962215406065513ce72a16 (diff) | |
parent | be4d069c58489afcd09d7b41b8b7cd27a7ef635f (diff) |
Merge pull request #978 from kamidox/master
Add two swift feature and make a full translation for swift to zh-cn
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 |