Swift--控制流與oc不一樣的地方

1.For-in循環中...app

for index in 1...5 {ide

    print("\(index) times 5 is \(index * 5)")oop

}this

for _ in 1...5 {spa

    能夠用下劃線忽略當前值
部署

}it

2.字典經過元祖返回io

3.do while循環變成repeatast

repeat {class

    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

}

在它通常的形式中,可用性條件使用了一個平臺名字和版本的列表。平臺名字能夠是iOSmacOSwatchOStvOS——請訪問聲明屬性來獲取完整列表。除了指定像 iOS 8的主板本號,咱們能夠指定像iOS 8.3 以及 macOS 10.10.3的子版本號。

相關文章
相關標籤/搜索