Sunday, February 21, 2016

Unique swift syntax

 1. Nil Coalescing Operator:  a??b  
The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

a??b
is shorthand for the code below:
a != nil ? a! : b

2. Inclusive Range Operator: for i in a...b {} 

The closed range operator (a...b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.

for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}

3. Half-Open Range Operator:  for i in a..<b {} 

The half-open range operator (a..<b) defines a range that runs from a to b, but does not include b. It is said to be half-open because it contains its first value, but not its final value.
for index in 1..<5 {
    print("\(index) times 5 is \(index * 5)")
}

4. Stride
The stride provides steps to loop through a range, either including the last value (through) or excluding the last value
for num in stride(from: 1000, through: 0, by: -100)  {
    print(num)

}

5. Argument and Parameter names for  function
In a method declaration, if the argument (external name) is specified, then when calling the method, the caller must specify the argument name. In order to skip the argument name, set the name to _ in function definition.

func someFunction(_ firstParameterName: Int, _ secondParameterName: Int)  {
    // function body goes here
    // firstParameterName and secondParameterName refer to
    // the argument values for the first and second parameters
}
someFunction(1, 2)

6. Parameter name for Closure
When defining closure variable, only parameter type information is specified, the argument names are skipped as the proper parameter names should be decided by the particular closure or function implementation, and the names are specified when defining the closure implementation body as shown below

    var handlerWithParamAndValue : (Int, String) -> String  =  {pi, ps in
        return pi.description + " " + ps
    }


let k = handlerWithParamAndValue(1, "yes")
print("the value is \(k)") 

7: try, try?, try! expression
try before an expression indicates the expression may throw exception.

try? before an expression indicates the expression returns an optional value. And if an error is thrown while evaluating the expression, the optional value is set to nil, and the error is eaten silently

try! before the expression indicates even if theoretically the expression may throw an error, but in this particular call, it will never throw an error.

8. In for in loop, add a where clause to only loop through the items that match certain condition, for example
for data in numbers where data % 2 == 0 {
    print(data)
}

This follows the same syntax as extension definition
extension Array where Element : Equable {
...
}

No comments:

Post a Comment