Saturday, June 7, 2014

[iOS] Learning note: Swift new features - constant, variable, control and function

Use let to make a constant and var to make a variable

* Use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value as optional
  • var optionalString: String? = "Hello"
  • optionalString == nil
  • var optionalName: String? = "John Appleseed"
  • var greeting = "Hello!"
  • if let name = optionalName {
  • greeting = "Hello, \(name)"
  • }

* Switch don't need "break" any more
  • let vegetable = "red pepper"
  • switch vegetable {
  • case "celery":
  • let vegetableComment = "Add some raisins and make ants on a log."
  • case "cucumber", "watercress":
  • let vegetableComment = "That would make a good tea sandwich."
  • case let x where x.hasSuffix("pepper"):
  • let vegetableComment = "Is it a spicy \(x)?"
  • default:
  • let vegetableComment = "Everything tastes good in soup."
  • }

You use for-in to iterate over items in a dictionary by providing a pair of names to use for each key-value pair
  • let interestingNumbers = [
  • "Prime": [2, 3, 5, 7, 11, 13],
  • "Fibonacci": [1, 1, 2, 3, 5, 8],
  • "Square": [1, 4, 9, 16, 25],
  • ]
  • var largest = 0
  • for (kind, numbers) in interestingNumbers {
  • for number in numbers {
  • if number > largest {
  • largest = number
  • }
  • }
  • }

Use a tuple to return multiple values from a function
  • func getGasPrices() -> (Double, Double, Double) {
  • return (3.59, 3.69, 3.79)
  • }

*. Functions can be nested
  • func returnFifteen() -> Int {
  • var y = 10
  • func add() {
  • y += 5
  • }
  • add()
  • return y
  • }

*. Function can return another function as its value
  • func makeIncrementer() -> (Int -> Int) {
  • func addOne(number: Int) -> Int {
  • return 1 + number
  • }
  • return addOne
  • }
  • var increment = makeIncrementer()

*. Function can take another function as one of its arguments
  • func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {
  • for item in list {
  • if condition(item) {
  • return true
  • }
  • }
  • return false
  • }
  • func lessThanTen(number: Int) -> Bool {
  • return number < 10
  • }
  • var numbers = [20, 19, 7, 12]
  • hasAnyMatches(numbers, lessThanTen)

*. Functions are actually a special case of closures. You can write a closure without a name by surrounding code with braces ({}). Use in to separate the arguments and return type from the body
  • numbers.map({
  • (number: Int) -> Int in
  • let result = 3 * number
  • return result
  • })
  • or
  • numbers.map({ number in 3 * number })

*. You can refer to parameters by number instead of by name
  • sort([1, 5, 3, 12, 2]) { $0 > $1 }



No comments:

Post a Comment