这篇文章主要讲解了“如何使用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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。