%:求餘數

7 % 3      
//得到結果:1

For in + where

程式範例用%加for迴圈,求得單/雙數

程式範例求雙數:
for index in 1...10 where index % 2 == 0 {
    print(index)
    //跑迴圈1~100,符合(where)後面的條件:除以2,餘數=0(代表雙數)
    //得到結果:2,4,6,8,10
}

練習:%加for迴圈,求1~100的單數

程式碼解答:

for index in 1...10 where index % 2 != 0 {
    print(index)
    //跑迴圈1~100,除以2不等於0(代表單數)
}

練習題:如何印出字典裡的每個鍵值對?

var stuffDict = ["red":"car","white":"Eggs","yellow":"Ball"]

解答:

var stuffDict = ["red":"car","white":"Eggs","yellow":"Ball"]

for (key, value) in stuffDict{
    print(key + ":" + value)
    //印出每一個鍵值對
}

補充:

  () 在swift叫Tuple 元組,以下示範取值。

var bonus = (100,200,300)
bonus.0
//會得到結果:100
bonus.2
//會得到結果:300

在陣列裡,得存相同的型別。

在元組裡,則無此限制。

練習:請根據下方程式碼,取出red的值

let someTuple = ("Hello", 3,1415, true, ["red","apple"])

解答

let someTuple = ("Hello", 3,1415, true, ["red","apple"])
//元組裡面可同時存在,字串、數值、布林、鍵值對
someTuple.3
//取得第四個位置的值["red", "apple"]

someTuple.3[0]
//取得第四個位置的第一個值:"red"

someTuple.3[1]
//取得第四個位置的第二個值:"apple"

補充:

var stuff = (red:"car",white:"Eggs",yellow:"Ball")
//Tuple也可以像字典一樣有鍵值

stuff.red
//取得red的值"car"

stuff.0
//取得第一格的值"car"

雖然tuple很像陣列又很像字典,但無法使用陣列及字典的功能,只是把資料包成一組一組,方便使用而已,請比對下述程式碼:

var stuffDict = ["red":"car","white":"Eggs","yellow":"Ball"]
stuffDict["red"]
stuffDict["white"]
stuffDict["yellow"]

results matching ""

    No results matching ""