Skip to content

Instantly share code, notes, and snippets.

@AsceticMonk
Last active January 28, 2016 09:39
Show Gist options
  • Save AsceticMonk/038d244fc3d896ca3a5e to your computer and use it in GitHub Desktop.
Save AsceticMonk/038d244fc3d896ca3a5e to your computer and use it in GitHub Desktop.
Swift 1.2 langauge changes
import Foundation
/*
Improved Optional Binding: goodbye pyramid of doom
Code and note extracted from: http://nshipster.com/swift-1.2/ (slightly modified)
*/
// Before Swift 1.2
let a = "10".toInt()
let b = "5".toInt()
let c = "3".toInt()
if let a = a {
if let b = b {
if let c = c {
if c != 0 {
println("(a + b) / c = \((a + b) / c)")
}
}
}
}
// Swift 1.2
let x = "50".toInt()
let y = "5".toInt()
let z = "9".toInt()
if let x = x, y = y, z = z where c != 0 {
println("(x - y) / z = \((x - y) / z)")
}
// Note: Each binding is evaluated in turn, stopping if any of the attempted bindings is nil.
// Only after all the optional bindings are successful is the wehre clause checked.
// Later binding expressions can reference earlier bindings
func intoSpanish(number: Int) -> String? {
var spanish: String?
if (number <= 50) {
spanish = "Todo bien!"
}
return spanish;
}
if let x = x, translation = intoSpanish(x) {
println(translation)
}
// Support a single leading boolean condition
let name = "Jorge"
let nationality = "Argentina"
if count(name) > 4 && contains(["Argentina", "Mexico", "Peru", "Bolivia"], nationality),
let translation = intoSpanish(50) where !isEmpty(translation) {
println("Localized: \(translation)")
}
/*
Forced Failable Conversion with as!
*/
class SocialAccount {
let accountName: String
init(accountName: String) {
self.accountName = accountName
}
}
class TwitterAccount: SocialAccount {
let fullName: String
init(accountName:String, fullName: String) {
self.fullName = fullName
super.init(accountName: accountName)
}
}
class FacebookAccount: SocialAccount {
let isPage: Bool
init(accountName: String, isPage: Bool) {
self.isPage = isPage
super.init(accountName: accountName)
}
}
let account1: SocialAccount = TwitterAccount(accountName: "@vancity", fullName: "Vancouver")
let twitterAccount = account1 as! TwitterAccount
// Runtime error!
// let facebookAccount = account1 as! FacebookAccount
let account2: SocialAccount = FacebookAccount(accountName: "Alex", isPage: false)
if let facebookAccount = account2 as? FacebookAccount {
print("FB account \(facebookAccount.accountName). Is it a page? \(facebookAccount.isPage)")
}
// as is used for upcast, type annotation and bridging conversion, checked at compile time
func out(s: String) {
println(s)
}
let ns: NSString = "Apple Watch"
// Note: implicit converstion from bridged Objective-C classes to their corresponding
// Swift value types have been removed. (NSString->String, NSArray->Array, NSDictionary->Dictionary)
//out(ns) // No longer works
// Bridging conversion
out(ns as String)
/*
New Collection Type: Set
*/
var team: Set<String> = []
team.insert("George")
team.insert("Peter")
team.insert("Greg")
team.insert("Alex")
team.insert("Peter")
println("Team has \(team.count) members");
// Some Set operations
// Code from: http://airspeedvelocity.net/2015/02/11/changes-to-the-swift-standard-library-in-1-2-beta-1/
let alphabets = Set("abcdefghijklmnopqrstuvwxyz")
println("There are \(alphabets.count) alphabets")
let consonants = alphabets.subtract("aeiou")
println("There are \(consonants.count) consonants")
consonants.isSubsetOf("abcdefghijklmnopqrstuvwxyz") // true
// Creating a new set
let newTeam = team.union(["Nancy", "Fernando"])
println("Old team has \(team.count) members");
println("New team has \(newTeam.count) members");
// Mutating the existing set
team.unionInPlace(["Nancy", "Fernando"])
team.contains("Nancy") // true
team.subtractInPlace(["Fernando"])
team.contains("Fernando") // false
/*
Constants: Deferred initialization of let constants
*/
// With Swift 1.2, this is possible
// Unfortunately there is a known issue with the new let behavior not working in a global scope
// rdar://19770775
/*let englishSpeaking = false
let myName: String
if englishSpeaking {
myName = "George"
} else {
myName = "Jorge"
}
println("My name is \(myName).")*/
// Workaround
func myName(#spanish: Bool) -> String {
let myName: String
if spanish {
myName = "Jorge"
} else {
myName = "George"
}
return myName
}
println("My name is \(myName(spanish: true))")
/*
Other Swift 1.2 related writings:
- http://adcdownload.apple.com//Developer_Tools/Xcode_6.3_beta_2/Xcode_6.3_beta_2_Release_Notes.pdf
- https://developer.apple.com/swift/blog/?id=22
- http://www.raywenderlich.com/95181/whats-new-in-swift-1-2
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment