Swift 1.2:
println("Hello World")
Swift 2.0:
print("Hello World")
P/S: Newline(\n) will automatically be appended
Control flow
Swift 1.2:
struct Person {
let name: String
let age: Int
let address: String?
}
func createPerson(jsonDict: [String: AnyObject]) -> Person? {
if let name: String = jsonDict["name"] as? String,
let age: Int = jsonDict["age"] as? Int,
let address: String = jsonDict["address"] as? String {
return Person(name: name, age: age, address: address)
} else {
return nil
}
}
P/S: There is a problem here, address is an optional, so it should not be in the optional chaining for the if let. So if we want to fit the code design, it would be like:
func createPerson(jsonDict: [String: AnyObject]) -> Person? {
let name: String? = jsonDict["name"] as? String
if name == nil {
return nil
}
let age: Int? = jsonDict["age"] as? Int
if age == nil {
return nil
}
let address: String? = jsonDict["address"] as? String
return Person(name: name!, age: age!, address: address)
}
This will generate the result that we wanted, Person will always be created so long as name and age is present, however, there are two problems:
1) In a bigger struct, the optional checks may be messy
2) we are forced to unwrap the name and age forcefully(even though it's safe, it's still ugly)
Swift 2.0 introduces Guard, which lets you execute the logic if the boolean expression is false and lets you exit earlier
func createPerson(jsonDict: [String: AnyObject]) -> Person? {
guard let name = jsonDict["name"] as? String, let age = jsonDict["age"] as? String else {
return nil
}
let address: String? = jsonDict["address"] as? String
return Person(name: name, age: age, address: address)
}
Summary: if guard condition is met, the code outside the braces are executed, if it isn't then the code inside the braces will be executed
IMPORTANT: make sure a control transfer statement is added at the end of the else clause(return/break/continue), otherwise call a function or method that doesn't return to the normal scope
Do-while
Do-while has been renamed to repeat-while
Pattern Matching
Swift 1.2
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for n in numbers {
if n % 2 == 0 {
print(n)
}
}
Swift 2.0
for n in numbers where n % 2 == 0 {
println(n)
}
Swift 1.2
enum Directions {
case Forward, Reverse, Left, Right
}
let movements: [Directions] = [.Forward, .Right, .Left, .Right, .Forward]
for movement in movements {
if movement == .Right {
println("Making a right turn")
}
}
Swift 2.0
for case .Right in movements {
println("Making a right turn")
}
No comments:
Post a Comment