Swift和Java控制流比較

1. Swift中for in循環和Java中foreach很相似,均可以簡化對集合的遍歷操做。安全

Swift語法:spa

  for index in 1...5{
            print("the index is \(index)")
        }
        
        let base = 3
        let power = 3
        var answer = 1
        for _ in 1...power {
            answer *= base
      }
        print("\(base) to the power of \(power) is \(answer)")
        // 輸出 "3 to the power of 10 is 59049"

Java語法以下:code

      ArrayList<String> array = new ArrayList<String>();
        array.add("a");
        array.add("b");
        array.add("c");
        array.add("d");
        for(String item: array){
            System.out.println(item);
        }

2. for條件遞增blog

Siwft和Java語法很相似,只是Swift語法沒有括號而已ip

Swift語法以下:it

for var index = 0; index < 3; ++index{
            print("index = \(index)")
        }

注意index在循環結束後最終的值是3而不是2。最後一次調用遞增表達式++index會將index設置爲3,從而致使index < 3條件爲false,並終止循環。io

Java語法以下:class

for(int index = 0; index < 3; index++){
            System.out.println("index = " + index);
        }

3. Switch....case語法變量

Swift和Java語法差很少,Swift不用寫break關鍵字,可是Swift支持更多case比較,下面是Swift代碼:foreach

let someCharacter : Character = "e"
        switch someCharacter{
        case "a", "e", "i", "o", "u":
            print("\(someCharacter) is a vowel")
        case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
        "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
            print("\(someCharacter) is a consonant")
        default:
            print("\(someCharacter) is not a vowel or a consonant")
        }

在 Swift 中,當匹配的 case 分支中的代碼執行完畢後,程序會終止switch語句,而不會繼續執行下一個 case 分支。這也就是說,不須要在 case 分支中顯式地使用break語句。這使得switch語句更安全、更易用,也避免了因忘記寫break語句而產生的錯誤。每個 case 分支都必須包含至少一條語句。像下面這樣書寫代碼是無效的,由於第一個 case 分支是空的。

Java代碼以下:

       char someCharacter = 'e';
        switch (someCharacter){
        case 'e':
            System.out.println("");
        break;
        }

Swift支持區間匹配

代碼以下:

let count = 3_000_000_000_000
let countedThings = "stars in the Milky Way"
var naturalCount: String
switch count {
case 0:
    naturalCount = "no"
case 1...3:
    naturalCount = "a few"
case 4...9:
    naturalCount = "several"
case 10...99:
    naturalCount = "tens of"
case 100...999:
    naturalCount = "hundreds of"
case 1000...999_999:
    naturalCount = "thousands of"
default:
    naturalCount = "millions and millions of"
}
print("There are \(naturalCount) \(countedThings).")
// 輸出 "There are millions and millions of stars in the Milky Way."

Swift支持值綁定

let anotherPoint = (2, 0)
        switch anotherPoint {
        case (let x, 0):
            print("on the x-axis with an x value of \(x)")
        case (0, let y):
            print("on the y-axis with a y value of \(y)")
        case let (x, y):
            print("somewhere else at (\(x), \(y))")
        }
        // 輸出 "on the x-axis with an x value of 2"

case 分支的模式容許將匹配的值綁定到一個臨時的常量或變量,這些常量或變量在該 case 分支裏就能夠被引用了——這種行爲被稱爲值綁定(value binding)。

Swift支持Where關鍵字

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")
}
// 輸出 "(1, -1) is on the line x == -y"

在上面的例子中,switch語句會判斷某個點是否在綠色的對角線x == y上,是否在紫色的對角線x == -y上,或者不在對角線上。

 4. 控制轉移語句(Control Transfer Statements)

Swift:控制轉移語句改變你代碼的執行順序,經過它你能夠實現代碼的跳轉。Swift有四種控制轉移語句,關鍵字以下:continue、break、fallthrough、return。Java控制語句關鍵字少一個fallthrough,其餘關鍵字用法接近。關於fallthrough語法以下:

let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
    description += " a prime number, and also"
    fallthrough
default:
    description += " an integer."
}
print(description)
// 輸出 "The number 5 is a prime number, and also an integer."

若是integerToDescribe的值不屬於列表中的任何質數,那麼它不會匹配到第一個switch分支。而這裏沒有其餘特別的分支狀況,因此integerToDescribe匹配到包含全部的default分支中。

注意:
fallthrough關鍵字不會檢查它下一個將會落入執行的 case 中的匹配條件。fallthrough簡單地使代碼執行繼續鏈接到下一個 case 中的執行代碼,這和 C 語言標準中的switch語句特性是同樣的。

相關文章
相關標籤/搜索