1。 Methods
分为instance method 和 type method(class method in OC)
“An instance method has implicit access to all other instance methods and properties of that type”
“Local and External Parameter Names for Methods”
“Function parameters can have both a local name (for use within the function’s body) and an external name (for use when calling the function)”
Naming Convention:
“Specifically, Swift gives the first parameter name in a method a local parameter name by default, and gives the second and subsequent parameter names both local and external parameter names by default. ”
class Counter {
var count: Int = 0
func incrementBy(amount: Int, numberOfTimes: Int) {
count += amount * numberOfTimes
}
}
let counter = Counter()
counter.incrementBy(5, numberOfTimes: 3)
// counter value is now 15”
as if
func incrementBy(amount: Int, #numberOfTimes: Int) {
count += amount * numberOfTimes
}
“Modifying Value Types from Within Instance Methods”
“By default, the properties of a value type cannot be modified from within its instance methods.”
struct Point {
var x = 0.0, y = 0.0
<span style="color:#ff0000;">mutating</span> func moveByX(deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveByX(2.0, y: 3.0)
println("The point is now at (\(somePoint.x), \(somePoint.y))")
// prints "The point is now at (3.0, 4.0)”
struct Point {
var x = 0.0, y = 0.0
mutating func moveByX(deltaX: Double, y deltaY: Double) {
self = Point(x: x + deltaX, y: y + deltaY)
}
}
enum TriStateSwitch {
case Off, Low, High
mutating func next() {
switch self {
case Off:
self = Low
case Low:
self = High
case High:
self = Off
}
}
}
var ovenLight = TriStateSwitch.Low
ovenLight.next()
// ovenLight is now equal to .High
ovenLight.next()
// ovenLight is now equal to .Off”
2. Subscripts
subscript(index: Int) -> Int {
get {
// return an appropriate subscript value here
}
set(newValue) {
// perform a suitable setting action here
}
}
struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable<span style="color:#ff0000;">(</span>multiplier: 3<span style="color:#ff0000;">)</span>
println("six times three is \(threeTimesTable[6])")
// prints "six times three is 18”
3. Inheritance
override key word
不能同时重载 set 和 didset,如果要这样,都移到se中
@final 关键字
4. Initialization
“Properties of optional type are automatically initialized with a value of nil, indicating that the property is deliberately intended to have “no value yet” during initialization.”
“You can modify the value of a constant property at any point during initialization, as long as it is set to a definite value by the time initialization finishes.”
“Default Initializers
Swift provides a default initializer for any structure or base class that provides default values for all of its properties and does not provide at least one initializer itself. ”