您现在的位置是:首页 > 文章详情

Swift中的函数常见写法

日期:2018-04-18点击:434


这里不涉及函数作为参数和返回值的情况。

进军iOS开发了哈。

计划六一前,搞一个套H5的App出来,

靠谱么?


其实,看过了java,php,javascript,python,go之后,

再在看swift,感觉很亲切啊,

都是老熟人。


func greet(person: String) -> String { let greeting = "Hello, " + person + "!" return greeting } print(greet(person: "Anna")) print(greet(person: "Brian")) func sayHelloWorld() -> String { return "hello, world" } print(sayHelloWorld()) func greet2(person: String) { print("Hello, \(person)!") } greet2(person: "Dave") func printAndCount(string: String) -> Int { print(string) return string.characters.count } func printWithoutCounting(string: String) { let _ = printAndCount(string: string) } printAndCount(string: "Hello, world") printWithoutCounting(string: "Hello, world") func minMax(array: [Int]) -> (min: Int, max: Int)? { if array.isEmpty {return nil} var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin { currentMin = value } else if value > currentMax { currentMax = value } } return (currentMin, currentMax) } if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) { print("min is \(bounds.min) and max is \(bounds.max)") } func gt(person: String, from hometown: String) -> String { return "Hello \(person)! glad you could visit from \(hometown)." } print(gt(person: "Bill", from: "Cupertino")) func someFunc(_ firstP: Int, secondP: Int) { print(firstP + secondP) } someFunc(1, secondP: 5) func someFunc2(pWithoutD: Int, pWithD: Int = 12) { print(pWithoutD + pWithD) } someFunc2(pWithoutD: 5) func arithmeticMean(_ numbers: Double...) -> Double { var total: Double = 0 for number in numbers { total += number } return total / Double(numbers.count) } print(arithmeticMean(1, 2, 3, 4, 5)) print(arithmeticMean(3, 5.34, 12.38, 67, 21.97)) func swapTwoInts(_ a: inout Int, _ b: inout Int) { let temporaryA = a; a = b b = temporaryA } var someInt = 3 var anotherInt = 107 swapTwoInts(&someInt, &anotherInt) print("someInt is now \(someInt), and anotherInt is now \(anotherInt)") 


原文链接:https://yq.aliyun.com/articles/583120
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章