Difference between revisions of "Swift Intermediate"

From Hawk Wiki
Jump to: navigation, search
(Created page with "=Intermediate Swift= Reference https://developer.apple.com/videos/wwdc/2014/?id=402 WWDC Link ==Optional Type== <pre class="brush:c"> var optionalNumber = Int? //default init...")
 
(Optional Type)
Line 30: Line 30:
 
}
 
}
 
</pre>
 
</pre>
 
+
<h4>Optional Chaining</h4>
<h4>A more complicated example</h4>
+
Example Without Chaining: <br>
 +
<pre class="brush:c">
 +
var addressNumber: Int?
 +
if let home = paul.residence {
 +
  if let postalAddress = home.Address {
 +
    if let building = postalAddress.buildingNumber {
 +
      if let convertedNumber = building.toInt() {
 +
        addressNumber = converttedNumber
 +
      }
 +
    }
 +
  }
 +
}
 +
</pre>
 +
With Chaining<br>
 +
<pre class="brush:c">
 +
addressNumber = paul.residence?.address?.buildingNumber?.toInt()
 +
//addressNumber is still an optional value at this state
 +
//Combine again
 +
if let addressNumber = paul.residence?.address?.buildingNumber?.toInt() {
 +
  addtoDb("paul", addressNumber)
 +
}
 +
</pre>

Revision as of 00:12, 27 January 2015

Intermediate Swift

Reference [WWDC Link]

Optional Type

var optionalNumber = Int?
//default init to nil
optionalNumber = 9

Non-optional type cannot be nil

Example

func findIndexOfArray(needle: String, array: String[]) => Int? {
  for (index, value) in enumerate(array) {
    if value == needle {
      return index
    }
  }
  return nil
}
var neighbors = ["Alex", "Anna", "Madison"]
let index = findIndexOfArray("Alex", neighbors)
if index {
  println("Found \(neighbors[index!])") // noticing the !. The ! will unwrapping the value. Must check non-nil it before unwrap.
}
//Optional binding: Check and unwrap at same time
if let indexValue = findIndexOfArray("Alex", neighbors) {
  println("Found \(neighbors[indexValue])")
}

Optional Chaining

Example Without Chaining:

var addressNumber: Int?
if let home = paul.residence {
  if let postalAddress = home.Address {
    if let building = postalAddress.buildingNumber {
      if let convertedNumber = building.toInt() {
        addressNumber = converttedNumber
      }
    }
  }
}

With Chaining

addressNumber = paul.residence?.address?.buildingNumber?.toInt()
//addressNumber is still an optional value at this state
//Combine again
if let addressNumber = paul.residence?.address?.buildingNumber?.toInt() {
  addtoDb("paul", addressNumber)
}