Last active
August 29, 2015 14:26
-
-
Save tiagopog/03c82856859df4e0219e to your computer and use it in GitHub Desktop.
Swift - Class definition and hierarchy
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
class NamedShape { | |
var numberOfSides = 0 | |
var name: String | |
init(name: String) { | |
self.name = name | |
} | |
func simpleDescription() -> String { | |
return "A shape with \(numberOfSides) sides." | |
} | |
} | |
let namedShape = NamedShape(name: "my named shape") | |
class Square: NamedShape { | |
var sideLength: Double | |
init(sideLength: Double, name: String) { | |
self.sideLength = sideLength | |
super.init(name: name) | |
numberOfSides = 4 | |
} | |
func area() -> Double { | |
return sideLength * sideLength | |
} | |
override func simpleDescription() -> String { | |
return "A square with sides of length \(sideLength)." | |
} | |
} | |
let testSquare = Square(sideLength: 5.2, name: "my test square") | |
testSquare.area() | |
testSquare.simpleDescription() |
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
enum Rank: Int { | |
case Ace = 1 | |
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten | |
case Jack, Queen, King | |
func simpleDescription() -> String { | |
switch self { | |
case .Ace: | |
return "ace" | |
case .Jack: | |
return "jack" | |
case .Queen: | |
return "queen" | |
case .King: | |
return "king" | |
default: | |
return String(self.rawValue) | |
} | |
} | |
} | |
let ace = Rank.Ace | |
let aceRawValue = ace.rawValue | |
struct Statuses { | |
var inactive: Status | |
var active: Status | |
func toString() -> String { | |
return "Statuses: \(inactive) and \(active)" | |
} | |
} | |
let statuses = Statuses(inactive: .Inactive, active: .Active) | |
statuses.toString() |
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
protocol Person { | |
var gender: String { get } | |
func talkAboutMyself() -> String | |
} | |
class Male: Person { | |
var name: String | |
var gender: String = "male" | |
init(name: String) { | |
self.name = name | |
} | |
func talkAboutMyself() -> String { | |
return "I'm a \(gender) named \(name)" | |
} | |
} | |
let person = Male(name: "Tiago") | |
person.talkAboutMyself() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment