iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 5
0
Mobile Development

IOS Beginner's 30days 系列 第 5

Day5 函式

Function

函式是一個獨立的程式碼區塊,把會重複做的事情或特別長的程式碼區塊寫成函式後在呼叫,會讓程式的可讀性更高,也能有效地節省時間。

沒有參數及返回值的function

    func 函示名稱() {
        // code
    }

Ex.

func noInputOutputFunction() {
    print("This function don't have any input or output")
}

// 呼叫的方式
    noInputOutputFunction()

含有參數及返回值的function

    func 函示名稱(參數名稱: 參數型別) -> 返回值型別 {
        // code
    }

Ex.

func withInputOutputFunction(input: String) -> Bool {
    if input == "" {
        return false
    } else {
        return true
    }
    print(input)
}

// 呼叫的方式
// (1)
    let withoutInput = withInputOutputFunction(input: "")
    if withoutInput == false {
        print("You did not input anything.")
    }
    
// (2)
    let withInput = withInputOutputFunction(input: "An input")
    if withInput == true {
        print("Your input is \(input)")
    }

(1)的執行解果
https://ithelp.ithome.com.tw/upload/images/20200907/20129677kYGcs84E04.png
(2)的執行解果
https://ithelp.ithome.com.tw/upload/images/20200907/20129677ZgMvMZ9lZ7.png


上一篇
Day4 條件判斷式
下一篇
Day6 @IBOutlet
系列文
IOS Beginner's 30days 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言