Swift--控制流与oc不同的地方
1.For-in循環中...
for index in 1...5 {
? ? print("\(index) times 5 is \(index * 5)")
}
for?_?in?1...5?{
? ? 可以用下劃線忽略當前值
}
2.字典通過元祖返回
3.do while循環變成repeat
repeat {
? ? statements
} while condition
4.switch不需要break
let someCharacter: Character = "z"
switch someCharacter {
case "a":
? ? print("The first letter of the alphabet")
case "z":
? ? print("The last letter of the alphabet")
default:
? ? print("Some other character")
}
5.switch case的body不能為空
6.case可以帶區間
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
var naturalCount: String
switch approximateCount {
case 0:
? ? naturalCount = "no"
case 1..<5:
? ? naturalCount = "a few"
case 5..<12:
? ? naturalCount = "several"
case 12..<100:
? ? naturalCount = "dozens of"
case 100..<1000:
? ? naturalCount = "hundreds of"
default:
? ? naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
7.case的元祖表示
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
? ? print("(0, 0) is at the origin")
case (_, 0):
? ? print("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
? ? print("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2):
? ? print("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
? ? print("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
8.case加額外條件
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
? ? print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
? ? print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
? ? print("(\(x), \(y)) is just some arbitrary point")
}
9.case ?fallthrough貫穿
fallthrough關鍵字不會檢查它下一個將會落入執行的 case 中的匹配條件。fallthrough簡單地使代碼繼續連接到下一個 case 中的代碼
10.while加標簽
gameLoop: while square != finalSquare {
? ? diceRoll += 1
? ? if diceRoll == 7 { diceRoll = 1 }
? ? switch square + diceRoll {
? ? case finalSquare:
? ? ? ? // diceRoll will move us to the final square, so the game is over
? ? ? ? break gameLoop
? ? case let newSquare where newSquare > finalSquare:
? ? ? ? // diceRoll will move us beyond the final square, so roll again
? ? ? ? continue gameLoop
? ? default:
? ? ? ? // this is a valid move, so find out its effect
? ? ? ? square += diceRoll
? ? ? ? square += board[square]
? ? }
}
print("Game over!")
11.guard與if的區別
像if語句一樣,guard的執行取決于一個表達式的布爾值。我們可以使用guard語句來要求條件必須為真時,以執行guard語句后的代碼。不同于if語句,一個guard語句總是有一個else從句,如果條件不為真則執行else從句中的代碼。
guard let name = person["name"] else {
? ? return
}
12.檢測 API 可用性
Swift內置支持檢查 API 可用性,這可以確保我們不會在當前部署機器上,不小心地使用了不可用的API。
if #available(iOS 10, macOS 10.12, *) {
? ? // 在 iOS 使用 iOS 10 的 API, 在 macOS 使用 macOS 10.12 的 API
} else {
? ? // 使用先前版本的 iOS 和 macOS 的 API
}
在它一般的形式中,可用性條件使用了一個平臺名字和版本的列表。平臺名字可以是iOS,macOS,watchOS和tvOS——請訪問聲明屬性來獲取完整列表。除了指定像 iOS 8的主板本號,我們可以指定像iOS 8.3 以及 macOS 10.10.3的子版本號。
?
?
轉載于:https://www.cnblogs.com/huoran1120/p/6118409.html
總結
以上是生活随笔為你收集整理的Swift--控制流与oc不同的地方的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到拜菩萨是什么意思
- 下一篇: 梦到自己去纹身是什么意思