十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
这篇文章主要讲解了“如何使用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函数这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!