An example of Switch:
let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
let vegetableComment = "That would make a agood tea sandwich."
case let x where x.hasSuffix ("pepper"):
let vegetableComment = "Is it a spicy \ (x)?"
default:
let vegetableComment = "Everything tastes good in soup."
}
Compared with the traditional oc, there are some new features, it is very practical to accept it
No break
for
for-in
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25]
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number> largest {
largest = number
}
}
}
largest
while / do while keep consistent
Extended usage of other for
var firstForLoop = 0
for i in 0..3 {
firstForLoop + = i
}
firstForLoop
var secondForLoop = 0
for var i = 0; i <3; ++ i {
secondForLoop + = 1
}
secondForLoop
Used and applied… instead of .. contains upper value (the difference between <and <=)
Functions and Closures
func greet (name: String, day: String)-> String {
returrn "Hellop \ (name), today is \ (day)."
}
greet ("Bob", "Tuesday")
// Use tuple to return multiple values
func getGasPrices ()-> (Double, Double, Double) {
return (3.59, 3.69, 3.79)
}
getGasPrices ()
Func will use an array to collect multiple variables:
func sumOf (numbers: Int ...)-> Int {
var sum = 0
for number in numbers {
sum + = number
}
return sum
}
sumOf ()
sumOf (42, 597, 12)
Next time to write the function, a lot of T T
Swift Tour essay summary (4)