Monday, January 19, 2015

The Swift Programming Language Note 2 (From Closures to Subscripts)

The Swift Programming Language Note 2 (From Closures to Subscripts)
1. Closures
reversed = sorted(names, { (s1: String, s2: String) -> Bool in return s1 > s2 } )
reversed = sorted(names, { s1, s2 in return s1 > s2 } )
reversed = sorted(names, { $0 > $1 } )
reversed = sorted(names) { $0 > $1 } -- as a trailing closure
reversed = sorted(names, >)

func makeIncrementor(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    func incrementor() -> Int {
        runningTotal += amount
        return runningTotal
    }
    return incrementor
}
The return type of makeIncrementor is () -> Int. This means that it returns a function, rather than a simple value.
The function it returns has no parameters, and returns an Int value each time it is called.
let incrementByTen = makeIncrementor(forIncrement: 10)

functions and closures are reference types.
Whenever you assign a function or a closure to a constant or a variable, you are actually setting that constant or variable
to be a reference to the function or closure.

2. Enumerations
enum CompassPoint {
    case North
    case South
    case East
    case West
}
enum Planet {
    case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
Unlike C and Objective-C, Swift enumeration members are not assigned a default integer value when they are created.

enum Barcode {
    case UPCA(Int, Int, Int, Int)
    case QRCode(String)
}

enum ASCIIControlCharacter: Character {
    case Tab = "\t"
    case LineFeed = "\n"
    case CarriageReturn = "\r"
}
Here, the raw values for an enumeration called ASCIIControlCharacter are defined to be of type Character

num Planet: Int {
    case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
Auto-incrementation means that Planet.Venus has a raw value of 2, and so on.

3. Classes and Structures
Classes have additional capabilities that structures do not:
Inheritance enables one class to inherit the characteristics of another.
Type casting enables you to check and interpret the type of a class instance at runtime.
Deinitializers enable an instance of a class to free up any resources it has assigned.
Reference counting allows more than one reference to a class instance.
Structures are always copied when they are passed around in your code, and do not use reference counting
Structures and Enumerations Are Value Types
A value type is a type whose value is copied when it is assigned to a variable or constant, or when it is passed to a function.
Classes Are Reference Types
Unlike value types, reference types are not copied when they are assigned to a variable or constant, or when they are passed to a function.
Rather than a copy, a reference to the same existing instance is used instead.
=== “Identical to” means that two constants or variables of class type refer to exactly the same class instance.
== “Equal to” means that two instances are considered “equal” or “equivalent” in value, for some appropriate meaning
of “equal”, as defined by the type’s designer

The structure’s primary purpose is to encapsulate a few relatively simple data values.
The structure does not need to inherit properties or behavior from another existing type.
Swift’s String, Array, and Dictionary types are implemented as structures. This means that strings, arrays, and dictionaries are
copied when they are assigned to a new constant or variable, or when they are passed to a function or method.
If a computed property’s setter does not define a name for the new value to be set, a default name of newValue is used.

4. Properties
Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set,
even if the new value is the same as the property’s current value.
You have the option to define either or both of these observers on a property:
willSet is called just before the value is stored.
didSet is called immediately after the new value is stored.
You define type properties for value types with the static keyword, and type properties for class types with the class keyword.

5. Methods
Methods are functions that are associated with a particular type. Classes, structures, and enumerations can all define instance methods
Instance methods are functions that belong to instances of a particular class, structure, or enumeration.
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
    }
}
This incrementBy method has two parameters—amount and numberOfTimes. By default, Swift treats amount as a local name only, but treats
numberOfTimes as both a local and an external name. You call the method as follows:
let counter = Counter()
counter.incrementBy(5, numberOfTimes: 3)

Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself. You use the self
property to refer to the current instance within its own instance methods.

if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method.

6. Subscripts
Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence.
struct TimesTable {
    let multiplier: Int
    subscript(index: Int) -> Int {
        return multiplier * index
    }
}
let threeTimesTable = TimesTable(multiplier: 3)
println("six times three is \(threeTimesTable[6])")
// prints "six times three is 18"

No comments:

Post a Comment