美文网首页
Swift基础学习(函数)

Swift基础学习(函数)

作者: whbsspu | 来源:发表于2016-08-01 15:34 被阅读17次

函数结构

  • 函数结构
func 函数名(参数)-> 函数返回类型{
   函数体
}

函数类型

  • 多参数函数:参数之间用逗号(,)隔开
func halfOpenRangeLength(start: Int, end: Int) -> Int {
return end - start
}
println(halfOpenRangeLength(1, 10))
// prints "9"
  • 无参数函数:注意,即使一个函数不带有任何参数,函数名称之后也要跟着一对空括号()
func sayHelloWorld() -> String {
return "hello, world"
}
println(sayHelloWorld())
// prints "hello, world"
  • 无返回值参数:无返回值函数后面可以不加返回箭头( – >)和返回类型
func sayGoodbye(personName: String) {
println("Goodbye, \(personName)!")
}
sayGoodbye("Dave")
// prints "Goodbye, Dave!"
  • 多返回值函数:可以使用元组或者多返回值组成的复合作为返回值。
func count(string: String) -> (vowels: Int, consonants: Int, others: Int) {
var vowels = 0, consonants = 0, others = 0
for character in string {
switch String(character).lowercaseString {
case "a", "e", "i", "o", "u":
++vowels
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
++consonants
default:
++others
}
}
return (vowels, consonants, others)
}

外部参数名

  • 使用外部参数名称的初衷是为了在别人在调用函数时知道函数入参的目的。
func join(string s1: String, toString s2: String, withJoiner joiner: String)
-> String {
return s1 + joiner + s2
}

join(string: "hello", toString: "world", withJoiner: ", ")
// returns "hello, world"

如果一个入参既是内部参数又是外部参数,那么只要在函数定义时参数前加#前缀即可。

可变参数

当传入的参数个数不确定时,可以使用可以参数,只需要在参数的类型名称后加上点字符(...)。

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)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8, 19)
// returns 10.0, which is the arithmetic mean of these three numbers

注意:函数最多有一个可变参数的参数,而且必须出现在参数列表的最后以避免多参数调用时出现歧义。

输入输出参数

如果想用一个函数来修改参数的值,并且只在函数调用结束之后修改,则可以使用输入-输出参数。只要才参数定义时添加inout关键字即可表明是输入输出参数。

相关文章

  • Swift 语言基础

    Swift 语言基础 Swift语言介绍 Swift基础部分 第一个Swift程序 Swift没有main函数,第...

  • Swift基础学习(函数)

    函数结构 函数结构 函数类型 多参数函数:参数之间用逗号(,)隔开 无参数函数:注意,即使一个函数不带有任何参数,...

  • Swift5 基础教程与进阶合集

    Swift5 基础 Swift5 基础(一)Swift编译流程、基础语法、流程控制、函数、枚举[https://w...

  • Swift5.0 - day1-基础介绍与基本运算

    一、基础知识 1.1、Swift 不用编写main函数(本质上swift是有main函数的),Swift将全局范围...

  • Swift 学习笔记(一)

    swift学习笔记第一篇,主要常量,变量,数据类型,条件判断,循环, 函数等基础知识的汇总 大纲汇总 Swift ...

  • Swift-函数

    文章是根据The Swift Programming Language 来总结的,今天就学习一下最基础的函数用法,...

  • 构造函数

    空闲期正好是停下脚步学习的时候,对于我这种打野人员,基础太过薄弱。 这次看了Swift 构造函数 Swift中的构...

  • Swift5.x-闭包(中文文档)

    引言 继续学习Swift文档,从上一章节:函数,我们学习了Swift函数相关的内容,如函数的定义和使用、函数参数、...

  • Swift5.x-基本的操作(中文文档)

    引言 继续学习Swift文档,从上一章节:基础,我们学习了Swift基础,现在,我们学习Swift的基本操作。这一...

  • swift学习笔记②

    Swift学习笔记 - 文集 语法篇 一、函数 函数定义 Swift 定义函数使用关键字 func,functio...

网友评论

      本文标题:Swift基础学习(函数)

      本文链接:https://www.haomeiwen.com/subject/tonxsttx.html