• Checking API Availability
• Synthesized Headers
• Protocol Extension
• Error Handling
• And more…
What’s New in Swift 2.0
Apple always rolls out new API’s and classes
throughout the year.
How do we check for API & Class availability?
Checking API Availability in Swift
The old way:
if NSClassFromString("SFSafariViewControler") != nil {
let eHAdviceVC = SFSafariViewController(URL: url, entersReaderIfAvailable: true)
eHAdviceVC.delegate = self
presentViewController(eHAdviceVC, animated: true, completion: nil)
} else {
let eHAdviceVC = eHAdviceViewController(URL: url);
presentViewController(eHAdviceVC, animated: true, completion: nil)
}
Checking API Availability in Swift
Checking API Availability in Swift
The new way:
if #available(iOS 9, OS X 10.10, watchOS 2, *) {
let eHAdviceVC = SFSafariViewController(URL: url, entersReaderIfAvailable: true)
eHAdviceVC.delegate = self
presentViewController(eHAdviceVC, animated: true, completion: nil)
} else {
let eHAdviceVC = eHAdviceViewController();
presentViewController(eHAdviceVC, animated: true, completion: nil)
}
Synthesized header files:
Xcode 7 scans through your code and produces virtual header files
that summarize the exposed methods with none of the code
Documentation - Similar to Apple's own classes
How to generate synthesized headers in Xcode 7?
Xcode 7, go to Navigate > Generated Interface.
Synthesized Headers
Synthesized Headers
extension NSURLRequest: URLRequestConvertible {
public var URLRequest: NSURLRequest
}
func URLRequest(method: Method, URL: URLStringConvertible) -> NSURLRequest
/**
Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter
encoding.
:param: method The HTTP method.
:param: URLString The URL string.
:param: parameters The parameters. `nil` by default.
:param: encoding The parameter encoding. `.URL` by default.
:returns: The created request.
*/
public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding:
ParameterEncoding = .URL) -> Request
/**
Creates a request using the shared manager instance for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:returns: The created request.
*
Protocol Extensions
Protocols can be extended to provide method
and property implementations to conforming
types.
You can use protocol extensions to provide a
default implementation to any method or property
requirement of that protocol.
Protocol Extensions
Example:
let ageOfEmployees: [Int?] = [30, 32, nil, 45, 50, 12, 8, 25, nil]
extension SequenceType where Generator.Element: OptionalType {
var purify: [Self.Generator.Element.T] {
return self.map { $0.optional }.filter { $0 != nil }.map { $0! }
}
}
let ageOfEmployees: [Int?] = [30, 32, nil, 45, 50, 12, 8, 25, nil]
ageOfEmployees.purify
[30, 32, 45, 50, 12, 8, 25]
Error Handling
Example:
func refreshActivityFeed() {
let refreshToken = login()
loadActivityFeed(refreshToken)
updateUI()
}
Error Handling
The Old Way:
func refreshActivityFeed() {
let refreshToken:String? = login(username, error:&error)
if (error != nil) {
if let error = error {
switch (error.code) {
case ERROR_UNAUTHORIZED:
showLoginVC()
case ERROR_FORBIDDEN:
showErrorAlert()
case ERROR_NOT_FOUND:
showLoginVC()
default:
showErrorAlert()
}
}
} else {
// Fetch the most recent activity feeds from the server
// Parse and prepare data structure
// Update UI
loadActivityFeed(refreshToken!)
updateUI()
}
}
The New Way:
func refreshActivityFeed() {
do
{
let refreshToken = try login(username)
loadActivityFeed(refreshToken)
updateUI()
} catch (LoginError.ERROR_UNAUTHORIZED) {
showLoginVC()
} catch (LoginError.ERROR_FORBIDDEN) {
showErrorAlert()
} catch (LoginError.ERROR_NOT_FOUND) {
showLoginVC()
} catch {
showErrorAlert()
}
}
Error Handling
Error Handling
Representing Errors
• ErrorType is a protocol in the Swift Standard Library
• Any type that conforms to ErrorType can be thrown and caught
• Can make your own types conform as well
• enum is great for groups of related errors
enum LoginError : ErrorType {
case ERROR_UNAUTHORIZED
case ERROR_FORBIDDEN
case ERROR_NOT_FOUND
case ERROR_NOT_ALLOWED
case ErrorWithMessage(code: Int, message: String)
}
Throwing Errors:
enum VendingMachineError: ErrorType {
case InvalidSelection
case InsufficientFunds(required: Double)
case OutOfStock
}
func purchaseItemFromVendingMachine(item: VendingItem) throws -> Bool {
if item.count() > 0 {
// .....
return true
} else {
throw VendingMachineError.OutOfStock
}
}
Error Handling
Catching and Handling Errors:
func refreshActivityFeed() {
do
{
let refreshToken = try loginWithUserName(username)
loadActivityFeed(refreshToken)
updateUI()
} catch (LoginError.ERROR_UNAUTHORIZED) {
showLoginVC()
} catch (LoginError.ERROR_FORBIDDEN) {
showErrorAlert()
} catch (LoginError.ERROR_NOT_FOUND) {
showLoginVC()
} catch {
showErrorAlert()
}
}
Error Handling
Disabling Error Propagation:
try! loadConfiguration()
Error Handling
Specifying Cleanup Actions:
func processFile(filename: String) throws {
if exists(filename) {
do {
let file = try open(filename)
defer {
close(file)
}
while let line = try file.readline() {
...
}
} catch {
...
}
}
}
Error Handling

Swift LA Meetup at eHarmony- What's New in Swift 2.0

  • 1.
    • Checking APIAvailability • Synthesized Headers • Protocol Extension • Error Handling • And more… What’s New in Swift 2.0
  • 2.
    Apple always rollsout new API’s and classes throughout the year. How do we check for API & Class availability? Checking API Availability in Swift
  • 3.
    The old way: ifNSClassFromString("SFSafariViewControler") != nil { let eHAdviceVC = SFSafariViewController(URL: url, entersReaderIfAvailable: true) eHAdviceVC.delegate = self presentViewController(eHAdviceVC, animated: true, completion: nil) } else { let eHAdviceVC = eHAdviceViewController(URL: url); presentViewController(eHAdviceVC, animated: true, completion: nil) } Checking API Availability in Swift
  • 4.
    Checking API Availabilityin Swift The new way: if #available(iOS 9, OS X 10.10, watchOS 2, *) { let eHAdviceVC = SFSafariViewController(URL: url, entersReaderIfAvailable: true) eHAdviceVC.delegate = self presentViewController(eHAdviceVC, animated: true, completion: nil) } else { let eHAdviceVC = eHAdviceViewController(); presentViewController(eHAdviceVC, animated: true, completion: nil) }
  • 5.
    Synthesized header files: Xcode7 scans through your code and produces virtual header files that summarize the exposed methods with none of the code Documentation - Similar to Apple's own classes How to generate synthesized headers in Xcode 7? Xcode 7, go to Navigate > Generated Interface. Synthesized Headers
  • 6.
    Synthesized Headers extension NSURLRequest:URLRequestConvertible { public var URLRequest: NSURLRequest } func URLRequest(method: Method, URL: URLStringConvertible) -> NSURLRequest /** Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding. :param: method The HTTP method. :param: URLString The URL string. :param: parameters The parameters. `nil` by default. :param: encoding The parameter encoding. `.URL` by default. :returns: The created request. */ public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request /** Creates a request using the shared manager instance for the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. :param: URLRequest The URL request :returns: The created request. *
  • 7.
    Protocol Extensions Protocols canbe extended to provide method and property implementations to conforming types. You can use protocol extensions to provide a default implementation to any method or property requirement of that protocol.
  • 8.
    Protocol Extensions Example: let ageOfEmployees:[Int?] = [30, 32, nil, 45, 50, 12, 8, 25, nil] extension SequenceType where Generator.Element: OptionalType { var purify: [Self.Generator.Element.T] { return self.map { $0.optional }.filter { $0 != nil }.map { $0! } } } let ageOfEmployees: [Int?] = [30, 32, nil, 45, 50, 12, 8, 25, nil] ageOfEmployees.purify [30, 32, 45, 50, 12, 8, 25]
  • 9.
    Error Handling Example: func refreshActivityFeed(){ let refreshToken = login() loadActivityFeed(refreshToken) updateUI() }
  • 10.
    Error Handling The OldWay: func refreshActivityFeed() { let refreshToken:String? = login(username, error:&error) if (error != nil) { if let error = error { switch (error.code) { case ERROR_UNAUTHORIZED: showLoginVC() case ERROR_FORBIDDEN: showErrorAlert() case ERROR_NOT_FOUND: showLoginVC() default: showErrorAlert() } } } else { // Fetch the most recent activity feeds from the server // Parse and prepare data structure // Update UI loadActivityFeed(refreshToken!) updateUI() } }
  • 11.
    The New Way: funcrefreshActivityFeed() { do { let refreshToken = try login(username) loadActivityFeed(refreshToken) updateUI() } catch (LoginError.ERROR_UNAUTHORIZED) { showLoginVC() } catch (LoginError.ERROR_FORBIDDEN) { showErrorAlert() } catch (LoginError.ERROR_NOT_FOUND) { showLoginVC() } catch { showErrorAlert() } } Error Handling
  • 12.
    Error Handling Representing Errors •ErrorType is a protocol in the Swift Standard Library • Any type that conforms to ErrorType can be thrown and caught • Can make your own types conform as well • enum is great for groups of related errors enum LoginError : ErrorType { case ERROR_UNAUTHORIZED case ERROR_FORBIDDEN case ERROR_NOT_FOUND case ERROR_NOT_ALLOWED case ErrorWithMessage(code: Int, message: String) }
  • 13.
    Throwing Errors: enum VendingMachineError:ErrorType { case InvalidSelection case InsufficientFunds(required: Double) case OutOfStock } func purchaseItemFromVendingMachine(item: VendingItem) throws -> Bool { if item.count() > 0 { // ..... return true } else { throw VendingMachineError.OutOfStock } } Error Handling
  • 14.
    Catching and HandlingErrors: func refreshActivityFeed() { do { let refreshToken = try loginWithUserName(username) loadActivityFeed(refreshToken) updateUI() } catch (LoginError.ERROR_UNAUTHORIZED) { showLoginVC() } catch (LoginError.ERROR_FORBIDDEN) { showErrorAlert() } catch (LoginError.ERROR_NOT_FOUND) { showLoginVC() } catch { showErrorAlert() } } Error Handling
  • 15.
    Disabling Error Propagation: try!loadConfiguration() Error Handling
  • 16.
    Specifying Cleanup Actions: funcprocessFile(filename: String) throws { if exists(filename) { do { let file = try open(filename) defer { close(file) } while let line = try file.readline() { ... } } catch { ... } } } Error Handling