Skip to content

Instantly share code, notes, and snippets.

@phynet
Last active August 29, 2015 14:24
Show Gist options
  • Save phynet/57b3c6548dd8948423f9 to your computer and use it in GitHub Desktop.
Save phynet/57b3c6548dd8948423f9 to your computer and use it in GitHub Desktop.
Swift Cheat Page

##Extension A Swift extension is similar to an Objective-C category. Extensions expand the behavior of existing classes, structures, and enumerations, including those defined in Objective-C.

extension Double {
   var km: Double { return self * 1_000.0 }
   var m: Double { return self }
   var cm: Double { return self / 100.0 }
   var mm: Double { return self / 1_000.0 }
   var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
print("One inch is \(oneInch) meters")
// prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
print("Three feet is \(threeFeet) meters")
// prints "Three feet is 0.914399970739201 meters"

##Closures Closures (blocks in objective-c) can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables, hence the name “closures”. Swift handles all of the memory management of capturing for you.

{ (parameters) -> return type in
    statements
}

###How to use closures with swift's lib Sort Swift’s standard library provides a function called sort, which sorts an array of values of a known type, based on the output of a sorting closure that you provide. The sorting closure needs to return true if the first value should appear before the second value, and false otherwise.

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]

#Using a standard function to sort the array

func backwards(s1: String, s2: String) -> Bool {
    return s1 > s2
}

var reversed = names.sort(backwards)

#refactor with closure. The start of the closure’s body 
#is introduced by the in keyword

reversed = names.sort({ (s1: String, s2: String) -> Bool in
      return s1 > s2
})

#Swift can infer the types of its parameters.
#because all of the types can be inferred, the return arrow (->) and 
#the parentheses around the names of the parameters can also be omitted:

reversed = names.sort( { s1, s2 in return s1 > s2 } )

let completionBlock: (NSData, NSError) -> Void = {
        data, error in /* ... */
    }

More info: Apple Developer Doc

##Convenience init TODO

##Params

Same names for local and external parameter names.

func power(#base: Int, #exponent: Int) -> Int {
   var result = base
 
  for _ in 1..<exponent {
    result = result * base
  }
 
   return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment