使用Playground快速练习Swift语法--函数的使用

函数定义和调用

func sayHello(personName: String) -> String {
  let greeting = "Hello," + personName + "!"
  return greeting
}

print(sayHello("阳春面"))

多重返回值函数

这个是在Java里期盼了好多年都没实现的功能。。。

func getMyInfo() -> (name:String,age:Int){
  let name = "阳春面"
  let age = 30
  return (name,age)
}

let myInfo = getMyInfo()
print("name: \(myInfo.name),age: \(myInfo.age)")

实际上,就是返回了一个元组(tuple)类型,这是多返回值的变相实现~~~

指定外部调用函数参数名

func join(string s1: String,toString s2: String,withJoiner joiner: String = " ") -> String {
  return s1 + joiner + s2
}

join(string: "hello",toString: "world",withJoiner: "-")

Swift 1.0中支持的#参数名这种默认外部参数的写法在2.0里已经不支持了。

可变参数

在参数类型后面加"..."代表可变参数,相当于传入的是个数组类型

func arithmeticMean(numbers: Double...) -> Double {
  var total: Double = 0
  for number in numbers {
    total += number
  }
  return total / Double(numbers.count)
}
arithmeticMean(1,2,3,4,5)

In-Out参数

通过inout修饰的参数,实际上传入的是引用,函数外部的变量会在函数体中被修改掉。

func swapTwoInts(inout a: Int,inout b: Int) {
  let temporaryA = a
  a = b
  b = temporaryA
}

var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt,b: &anotherInt)
print("someInt is now \(someInt),and anotherInt is now \(anotherInt)")

函数类型

func addTwoInts(a: Int,b: Int) -> Int {
  return a + b
}
var mathFunction: (Int,Int) -> Int = addTwoInts

这个可以读作:“定义一个叫做mathFunction的变量,类型是‘一个有两个Int
型的参数并返回一个Int型的值的函数’,并让这个新变量指向addTwoInts函数”。

函数类型完全象一个变量类型一样,还可以作为参数和返回值。

嵌套函数

嵌套函数只在父函数内部可见,但也可以被父函数作为返回值返回到外部,
使得这个函数可以在外部被使用。。

func chooseSayHelloFunction(lang: String) -> (String) -> String{
  func sayHelloInChinese(name: String) ->String{
    return "你好 "+name
  }
  func sayHelloInEnglish(name: String) -> String{
    return "hello "+name

  }
  return lang == "cn" ? sayHelloInChinese: sayHelloInEnglish
}

let sayHelloInChinese = chooseSayHelloFunction("cn")
print(sayHelloInChinese("阳春面"))

参考资料

The Swift Programming Language 中文版
The Swift Programming Language 2.0 官方教程

中文版的教程有些老了,还是基于Swift 1.0的,有些函数已经发生了变化,可以对照看官方教程。

本文作者: 阳春面
原文地址:http://www.aswifter.com/2015/07/15/learn-swift-with-playground-func/

欢迎关注我的微信公众号,分享Android 开发,IOS开发,Swift开发和互联网内容
微信号:APP开发者

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...