Swift初体验-函数与闭包
来源:互联网 发布:上海浦东java培训机构 编辑:程序博客网 时间:2024/06/02 06:54
//: [Previous](@previous)// 函数和闭包import Foundation/** 函数格式: func 函数名称(参数) -> 返回值 { } 1. 函数都是以 func 开头来声明 2. 返回值以 -> 来指定 */func greet(person:String, day:String) -> String { return "hello \(person), today is \(day)"}greet(person: "Bob", day: "Tuesday")/** 外部参数名 & 内部参数名 1. 系统默认使用参数名称当做外部参数名称,例如: greet(person: "Bob", day: "Tuesday") 2. 外部参数名可以自定义, 也可以使用 _ 来表示 不使用外部参数名 */func greetA(_ person:String, on day:String) -> String { return "Hello \(person), today is \(day)"}greetA("John", on: "Wednesday")/** 元组: 1. 元组可以让函数返回多个值 2. 访问元组的元素可以使用名称 或者 数组来表示 3. 函数带可变个数的参数,"这些参数在函数内表现为数组的形式" */// func calculatStatistics(scores:[Int]) -> (min: Int, max:Int, sum:Int)func calculatStatistics(scores : Int...) -> (min: Int, max:Int, sum:Int){ var min = scores[0] var max = scores[0] var sum = 0 for score in scores { if score > max { max = score } else if score < min { min = score } sum += score } return (min, max, sum)}//let statistics = calculatStatistics(scores: [5, 3, 100, 3, 9])let statistics = calculatStatistics(scores: 5, 3, 100, 3, 9)print(statistics.min)print(statistics.1)print(statistics.sum)/** 函数嵌套: 1. 函数可以嵌套 2. 嵌套的函数可以访问被嵌套 */func returnFifteen() ->Int { var y = 10 func add() { y += 5 } y = 15 add() return y}returnFifteen()/** 函数作为返回值 & 参数 Swift之中,函数当做 返回值 & 参数的时候,提示很不友好,建议分步写完 */func makeIncrementer() ->((Int) -> Int) { func addOne(number : Int) -> Int { return 1 + number; } return addOne}var increment = makeIncrementer()increment(7)func hasAnyMatches(list:Int..., condition:(Int) -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false}func lessThanTen(number:Int) ->Bool { return number < 10}hasAnyMatches(list: 20,19,7,12, condition: lessThanTen)/** 闭包: 1. 函数是一种特殊的闭包 2. 如果一个闭包的类型已知,可以忽略参数的类型 和返回值 3. “单个”语句闭包会把它语句的值当做结果返回 4. 可以通过参数位置而不是参数名字来引用参数——这个方法在非常短的闭包中非常有用 5. 当一个闭包作为“最后一个参数”传给一个函数的时候,它可以直接跟在括号后面, “尾随闭包” */var numbers = [10, 30, 50, 100]numbers.map { (number : Int) -> Int in let result = 3 * number return result}numbers.map { number in 3 * number}// 尾随闭包numbers.sort { (number1, number2) -> Bool in return number1 > number2}// “单个”语句闭包会把它语句的值numbers.sort { (number1, number2) -> Bool in number1 > number2}numbers.sort { $0 > $1}//: [Next](@next)
0 0
- Swift初体验-函数与闭包
- Swift闭包与函数
- 函数与闭包(Swift)
- Swift 函数与闭包
- swift的函数与闭包
- swift闭包函数
- javascript函数闭包之初体验~~~
- Swift简明教程(三)-函数与闭包
- Swift之旅(三)函数与闭包
- 窥探Swift之函数与闭包的应用实例
- 窥探 Swift 之 函数与闭包的应用实例
- Object-C--->Swift之(七)嵌套函数与闭包
- swift 函数和闭包
- Swift函数和闭包
- Swift 函数,闭包使用
- Swift函数和闭包
- Swift 函数和闭包
- Swift-Swift初体验
- javascript面向对象
- STA优化
- Qt Stylesheets Button Bar
- java 五种创建对象的方法
- 卡巴斯基发布操作系统Kaspersky OS
- Swift初体验-函数与闭包
- sql使用技巧-2
- 设计师要懂布局(二)
- 查看表空间,表空间路径,增加表空间 2015-06-11 15:13:46 分类: Oracle select * from dba_tablespaces--查看表空间 select
- 448. Find All Numbers Disappeared in an Array
- hihoCoder 字符消除 (字符串处理)(枚举)
- 路径/\问题
- iOS - Xcode 语言国际化步骤
- 说说JS中的浅拷贝与深拷贝