Swift 中的函数
来源:互联网 发布:在淘宝网上开店要钱吗 编辑:程序博客网 时间:2024/06/17 13:18
想要使用函数,必须先声明后调用,Swift 中使用 func 关键字来定义函数,每个函数都有一个函数名,用于描述函数要执行的任务,有的函数也包括参数或者返回值。
函数的基本格式
func 函数名 (参数名1 : 参数类型, 参数名1 : 参数类型) -> 返回值类型 { 函数体 return 返回值 }
无参函数有返回值
func sayHello() -> String { return "HelloWorld"}
多参数有返回值
func sayHello(name : String, alreadyGreeted : Bool) -> String { if alreadyGreeted { return "Hello again \(name)" } else { return "Hello \(name)" }}
无参数无返回值函数
func test1() { print("---------");}func test2() -> Void { print("**********")}func test3() -> () { print("___****");}
多返回值函数
- 使用元组类型作为函数的返回值,可以让多个值作为一个复合值返回
func count(str: String) -> (vowels: Int,consonants:Int,other:Int) { var vowels = 0,consonants = 0,other = 0 for character in str.characters { switch String(character).lowercased() { case "a","e","i","o","u": //元音 vowels += 1 case "b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z": //辅音 consonants += 1 default: other += 1 } } return (vowels,consonants,other)}//调用count(str: "qasdfghjkjhfdfg1234567")
局部参数名和外部参数名
- 局部参数名
func someFunc(firstParam : Int,SecondParam : Int) {}someFunc(firstParam: 1, SecondParam: 2)
- 外部参数名
func compare(num1 x : Int, num2 y : Int) -> Int { return x > y ? x : y}compare(num1: 1, num2: 2)
默认参数值
func sayHi(message : String , name : String = "王二小") { print("\(name),\(message)")}sayHi(message: "hello")sayHi(message: "Hi", name: "小明")
可变参数
func arithmeticMean(numbers:Double...) ->Double { var total : Double = 0 for number in numbers { total += number } return total/Double(numbers.count)}//调用arithmeticMean(numbers: 12 ,12.12, 13.4, 15.6)
In-Out (输入输出)参数
- 一般参数仅仅是在函数内可以改变的,当这个函数只执行完毕后变量就被销毁了,如果想要通过一个函数修改参数的值,并且让这些修改在函数调用结束后仍存在,这时可以将这个参数定义为输入输出参数
func swapTwoInts(a : inout Int, b :inout Int) { let Temp = a; a = b b = Temp}var num1 = 3var num2 = 4swapTwoInts(a: &num1, b: &num2)输出num1 = 4num2 = 3
嵌套函数
func calculate(opr : String) ->(Int,Int) ->Int { func add(a : Int,b : Int) -> Int { return a + b } func sub(a : Int,b : Int) -> Int { return a - b } var result : (Int,Int) -> Int switch opr { case "+": result = add case "-": result = sub default: result = add } return result}//加法let f1:(Int,Int) -> Int = calculate(opr: "+")f1(1,3)//减法let f2:(Int,Int) -> Int = calculate(opr: "-")f2(1,3)
阅读全文
0 0
- Swift中的标准函数
- Swift中的函数
- Swift中的floor()函数
- 9. Swift 中的函数
- Swift中的柯里化函数
- swift中的函数
- Swift 中的函数
- Swift 中的方法(函数)
- Swift 中的floor()函数 用途
- Swift入门教程系列5-函数+selector在swift中的用法
- 【iOS】Swift中的函数、断言、枚举等
- swift中的函数的使用,嵌套
- Swift中的函数和闭包
- Swift语言中的控制语句和函数
- swift结构体中的构造函数
- Swift中的构造函数及其继承
- Swift 3.0中的函数签名与函数引用
- Swift 3.0中的函数签名与函数引用
- Android消息传递之Handler消息机制
- Sqlserver "with execute clause" 的研究
- bzoj2006: [NOI2010]超级钢琴
- protobuf入门教程(二):消息类型
- 论比特币发展史-一个比萨价值过亿!
- Swift 中的函数
- 深入浅出JMS(四)--Spring和ActiveMQ整合的完整实例
- react-native踩过的坑
- [LWIP学习]--SylixOS AF_UNIX socket套接字分析
- Android异常记录
- Spring及SpringBoot @Async配置步骤及注意事项
- 微信小程序豆瓣电影实例源码下载
- phpstudy本地测试出现nginx502
- 442