您好,登錄后才能下訂單哦!
這篇文章主要講解了“如何使用swift函數”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“如何使用swift函數”吧!
func greet(_ person: String = "zhang san", _ hometown: String = "bei jing") -> String { return "Hello \(person)! Glad you could visit from \(hometown)" } print(greet()) //Hello zhang san! Glad you could visit from bei jing
//不定參數個數 func sum(_ nums: Int...) -> Int { var ret = 0 for n in nums { ret += n } return ret } print(sum(1,2,3)) //6 print(sum(1,2,3,4,5)) //15
//函數內改變函數外定義的參數值 func swap(_ a: inout Int, _ b: inout Int) { let temp = a a = b b = temp } var a = 1 var b = 2 swap(&a, &b) print(a) //2 print(b) //1
func add(_ a: Int, _ b: Int) -> Int { return a + b } var addFunc: (Int, Int) -> Int = add print(addFunc(1, 2)) //3
func printResult(_ f: (Int, Int) -> Int, _ a: Int, _ b: Int) { print("Result: \(f(a, b))") } printResult(add, 1,2) //Result: 3
func forward(_ input: Int) -> Int { return input + 1 } func backward(_ input: Int) -> Int { return input - 1 } func step(isBack: Bool) -> (Int) -> Int { return isBack ? backward : forward } //記數倒數到0 var currValue = 3 let moveNearerToZero = step(isBack: currValue > 0) print("Counting to zero:") while currValue != 0 { print("\(currValue)...") currValue = moveNearerToZero(currValue) } print("zero!") /* Counting to zero: 3... 2... 1... zero! */
func chooseStepFunc(backward: Bool) -> (Int) -> Int { func stepForward(input: Int) -> Int { return input + 1 } func stepBackward(input: Int) -> Int { return input - 1 } return backward ? stepBackward : stepForward } print("Counting to zero:") var cVal = -4 let toZero = chooseStepFunc(backward: cVal > 0) while cVal != 0 { print("\(cVal)...") cVal = toZero(cVal) } print("zero!") /* Counting to zero: -4... -3... -2... -1... zero! */
感謝各位的閱讀,以上就是“如何使用swift函數”的內容了,經過本文的學習后,相信大家對如何使用swift函數這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。