寒城攻略:Listo 教你 25 天学会 Swift 语言 - 08 Functions
2014-07-16 09:29
411 查看
import Foundation
//***********************************************************************************************
//1.Functions(函数)
//_______________________________________________________________________________________________
//介绍
/*
函数是用来完成特定任务的独立代码块。给一个函数起一个适合的名字,用来标识函数是做什么的,当函数执行时,调用函数名即可
Swift 中的函数语法灵活,可以用来表示任何函数,包括从最简单的没有参数名的 C
风格函数,到复杂带局部和外部参数名的 Objective-C 风格函数。参数可以提供默认值,以简化函数调用。参数既可以当作传入参数,也可以当作传出参数,也就是说,一旦函数执行结束,传入的参数值可以被修改
在 Swift 中,每个函数都有一种类型,包括函数的参数类型和返回值类型,你可以把函数类型当作任何其他普通类型一样处理,这样就可以把函数当作其他函数的参数,也可以从其他函数中返回函数。函数的定义可以写在其他函数的定义中,这样可以在嵌套函数范围内实现功能封装
*/
//***********************************************************************************************
//2.Defining and Calling Functions(定义和调用函数)
//_______________________________________________________________________________________________
//函数的定义和调用:以 func
作为前缀,返回剪头 "->" 表示函数的返回类型(func
函数名(形参) ->
返回值类型)
func sayHello(personName:
String) -> String{
let greeting = "Hello, " + personName +
"!"
return greeting
}
println(sayHello("Listo"))
//***********************************************************************************************
//1.Function Parameters and Return Values(函数的参数和返回值)
//_______________________________________________________________________________________________
//函数可以有多个输入参数
func minusResult(start:
Int, end: Int) ->
Int{ //函数可以有多个输入参数,在圆括号中用逗号分隔
return end - start
}
println(minusResult(1,
10))
//_______________________________________________________________________________________________
//无参函数
func sayHelloWorld() ->
String{
return
"hello world"
}
println(sayHelloWorld())
//_______________________________________________________________________________________________
//无返回值函数(严格的来说,虽然没有定义返回值, sayGoodbye
函数依然返回了值,没有定义返回类型的函数会返回一个特殊的值,叫做 Void。他其实是一个空的元组,没有任何的元素,可以写成 ())
func sayGoodbye(name:
String){
println("Goodbye,
\(name)")
}
println(sayGoodbye("Listo"))
//_______________________________________________________________________________________________
//多重返回值的函数(返回元组类型的函数)
func count(string:
String) -> (vs: Int, cs:
Int, os: Int) {
//定义返回值类型为元组类型
var vowels = 0
var consonants = 0
var 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)
}
let total =
count("some arbitrary string!")
println("\(total.vs) vowels and
\(total.cs) consonants")
//***********************************************************************************************
//3.Function Parameter Names(函数的参数名)
//_______________________________________________________________________________________________
//函数参数名称(局部参数名和外部参数名)
func join(s1:
String, s2: String, joiner:
String) -> String{
//此时 s1,s2,joiner
都是内部参数名,只能在函数的内部进行使用
return s1 + joiner + s2
}
println(join("hello",
"world",
","))
//内部参数名对应的不足是在调用函数的时候,我们没法知道调用函数实参的具体含义
func join1(string s1:
String, toString s2:
String, withJoiner joiner: String) ->
String{ //使用 string,toString,withJoiner
三个名称给函数内部形参命名作为外部参数名,可以在函数的外部进行使用
return s1 + joiner + s2
}
println(join1(string:
"hello", toString:
"world", withJoiner: ","))
//我们在调用函数的时候,使用外部参数名可以更明显的说明实参的含义
//_______________________________________________________________________________________________
//简写外部参数名(当外部参数名和内部参数名相同的时候,可以在局部参数名前面加上 "#"
来说明这个参数名是外部参数名和局部参数名
func join2(#string:
String, #toString:
String, #withJoiner: String) ->
String{
return string + withJoiner + toString
}
println(join2(string:
"hello", toString:
"world", withJoiner: ","))
//_______________________________________________________________________________________________
//函数参数默认值
func join3(#string:
String, #toString:
String, withJoiner:
String =
",") -> String{
//在设置函数参数时为参数设置默认值,在函数调用的时候可以不指定函数的实参,当设置默认值时,这个参数自动转化为外部参数名,在调用的时候必须声明外部参数名
return string + withJoiner + toString
}
println(join3(string:
"hello", toString:
"world", withJoiner: "-"))
//如果在调用函数的时候修改形参默认值,保留修改后的值
//_______________________________________________________________________________________________
//可变参数(当参数的数量不确定时,使用可变参数命名参数即可,一个函数最多能有一个可变参数,可变参数必须在参数的最后位置)
func airtheticMean(numbers:
Double...) -> Double{
var total: Double =
0
for number in numbers{
total += number
}
return total / Double(numbers.count)
}
println(airtheticMean(1.2,
3.5,
4.6))
//_______________________________________________________________________________________________
//常量参数和变量参数(函数参数默认为常量,如果需要在函数中修改参数,就要定义变量参数)
func alignRight(var string:
String, count: Int, pad:
Character) -> String{
//设置参数 string
为变量参数,在函数内部可以修改参数
let amountToPad = count -
countElements(string) //使用 "countElements"
函数获取字符串长度
for _
in 1...amountToPad{
string = pad + string
}
return string
}
let originalString =
"hello"
let paddedString =
alignRight(originalString,
10, "_")
println("originalString: " +
originalString)
println("paddedString: " +
paddedString)
//_______________________________________________________________________________________________
//输入输出参数(变量参数仅仅在函数体内被更改,如果想要一个函数可以修改参数的值,并且想要在函数调用结束之后依旧存在,那么就应定义输入输出参数)
func swapTwoInts(inout a:
Int,
inout b: Int){
//使用 inout
函数来定义输入输出参数,输入输出参数不能有默认值,可变的参数不能用 inout
标记
let temp = a
a = b
b = temp
}
var someInt =
3
var anotherInt =
8
swapTwoInts(&someInt, &anotherInt)
//在调用函数时,当传入的参数作为输入输出参数的时候,在参数前加上 &
,表示这个值可以被函数修改
println("someInt is now
\(someInt), another is now
\(anotherInt)")
//***********************************************************************************************
//4.Function Types(函数类型)
//_______________________________________________________________________________________________
//函数类型的写法分为三步:1.定义函数; 2.声明函数类型变量或者常量; 3.给函数类型变量赋值
func addTwoInts(a:
Int, b: Int) ->
Int{ //定义函数
return a + b
}
var mathFunction: (Int,
Int) -> Int
//声明函数类型变量
mathFunction =
addTwoInts
//给函数类型变量赋值
println("result:
\(mathFunction(2,
3))")
//输出函数类型的变量
//_______________________________________________________________________________________________
//函数类型作为参数类型
func printMathResult(mathFun: (Int,
Int) -> Int, a:
Int, b: Int){
println("Result:
\(mathFun(a, b))")
}
printMathResult(mathFunction,
4, 7)
//_______________________________________________________________________________________________
//函数类型作为返回类型
func stepForward(input:
Int) -> Int{
return input + 1
}
func stepBackward(input:
Int) -> Int{
return input - 1
}
func chooseStepFunction(backward:
Bool) -> (Int) ->
Int{
//声明 chooseStepFunction
函数返回函数类型数据,返回类型为 (Int) -> Int
return backward ?
stepBackward: stepForward
//返回函数类型
}
var currentValue =
3
let moveNearerToZero =
chooseStepFunction(currentValue >
0)
//此时 moveNearerToZero
= stepBackward 函数
println("moveNearerToZero:
\(moveNearerToZero(10))")
//_______________________________________________________________________________________________
//嵌套函数
func chooseStepFunction1(backward:
Bool) -> ((Int) ->
Int){
func stepForward1(input:
Int) -> Int{
return input + 1
}
func stepBackward1(input:
Int) -> Int{
return input - 1
}
return backward ?
stepBackward1: stepForward1
//返回函数类型
}
var currentValue1 =
8
let moveNearerToZero1 =
chooseStepFunction1(currentValue >
0)
//此时 moveNearerToZero
= stepBackward 函数
println("moveNearerToZero:
\(moveNearerToZero1(10))")
//***********************************************************************************************
//1.Functions(函数)
//_______________________________________________________________________________________________
//介绍
/*
函数是用来完成特定任务的独立代码块。给一个函数起一个适合的名字,用来标识函数是做什么的,当函数执行时,调用函数名即可
Swift 中的函数语法灵活,可以用来表示任何函数,包括从最简单的没有参数名的 C
风格函数,到复杂带局部和外部参数名的 Objective-C 风格函数。参数可以提供默认值,以简化函数调用。参数既可以当作传入参数,也可以当作传出参数,也就是说,一旦函数执行结束,传入的参数值可以被修改
在 Swift 中,每个函数都有一种类型,包括函数的参数类型和返回值类型,你可以把函数类型当作任何其他普通类型一样处理,这样就可以把函数当作其他函数的参数,也可以从其他函数中返回函数。函数的定义可以写在其他函数的定义中,这样可以在嵌套函数范围内实现功能封装
*/
//***********************************************************************************************
//2.Defining and Calling Functions(定义和调用函数)
//_______________________________________________________________________________________________
//函数的定义和调用:以 func
作为前缀,返回剪头 "->" 表示函数的返回类型(func
函数名(形参) ->
返回值类型)
func sayHello(personName:
String) -> String{
let greeting = "Hello, " + personName +
"!"
return greeting
}
println(sayHello("Listo"))
//***********************************************************************************************
//1.Function Parameters and Return Values(函数的参数和返回值)
//_______________________________________________________________________________________________
//函数可以有多个输入参数
func minusResult(start:
Int, end: Int) ->
Int{ //函数可以有多个输入参数,在圆括号中用逗号分隔
return end - start
}
println(minusResult(1,
10))
//_______________________________________________________________________________________________
//无参函数
func sayHelloWorld() ->
String{
return
"hello world"
}
println(sayHelloWorld())
//_______________________________________________________________________________________________
//无返回值函数(严格的来说,虽然没有定义返回值, sayGoodbye
函数依然返回了值,没有定义返回类型的函数会返回一个特殊的值,叫做 Void。他其实是一个空的元组,没有任何的元素,可以写成 ())
func sayGoodbye(name:
String){
println("Goodbye,
\(name)")
}
println(sayGoodbye("Listo"))
//_______________________________________________________________________________________________
//多重返回值的函数(返回元组类型的函数)
func count(string:
String) -> (vs: Int, cs:
Int, os: Int) {
//定义返回值类型为元组类型
var vowels = 0
var consonants = 0
var 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)
}
let total =
count("some arbitrary string!")
println("\(total.vs) vowels and
\(total.cs) consonants")
//***********************************************************************************************
//3.Function Parameter Names(函数的参数名)
//_______________________________________________________________________________________________
//函数参数名称(局部参数名和外部参数名)
func join(s1:
String, s2: String, joiner:
String) -> String{
//此时 s1,s2,joiner
都是内部参数名,只能在函数的内部进行使用
return s1 + joiner + s2
}
println(join("hello",
"world",
","))
//内部参数名对应的不足是在调用函数的时候,我们没法知道调用函数实参的具体含义
func join1(string s1:
String, toString s2:
String, withJoiner joiner: String) ->
String{ //使用 string,toString,withJoiner
三个名称给函数内部形参命名作为外部参数名,可以在函数的外部进行使用
return s1 + joiner + s2
}
println(join1(string:
"hello", toString:
"world", withJoiner: ","))
//我们在调用函数的时候,使用外部参数名可以更明显的说明实参的含义
//_______________________________________________________________________________________________
//简写外部参数名(当外部参数名和内部参数名相同的时候,可以在局部参数名前面加上 "#"
来说明这个参数名是外部参数名和局部参数名
func join2(#string:
String, #toString:
String, #withJoiner: String) ->
String{
return string + withJoiner + toString
}
println(join2(string:
"hello", toString:
"world", withJoiner: ","))
//_______________________________________________________________________________________________
//函数参数默认值
func join3(#string:
String, #toString:
String, withJoiner:
String =
",") -> String{
//在设置函数参数时为参数设置默认值,在函数调用的时候可以不指定函数的实参,当设置默认值时,这个参数自动转化为外部参数名,在调用的时候必须声明外部参数名
return string + withJoiner + toString
}
println(join3(string:
"hello", toString:
"world", withJoiner: "-"))
//如果在调用函数的时候修改形参默认值,保留修改后的值
//_______________________________________________________________________________________________
//可变参数(当参数的数量不确定时,使用可变参数命名参数即可,一个函数最多能有一个可变参数,可变参数必须在参数的最后位置)
func airtheticMean(numbers:
Double...) -> Double{
var total: Double =
0
for number in numbers{
total += number
}
return total / Double(numbers.count)
}
println(airtheticMean(1.2,
3.5,
4.6))
//_______________________________________________________________________________________________
//常量参数和变量参数(函数参数默认为常量,如果需要在函数中修改参数,就要定义变量参数)
func alignRight(var string:
String, count: Int, pad:
Character) -> String{
//设置参数 string
为变量参数,在函数内部可以修改参数
let amountToPad = count -
countElements(string) //使用 "countElements"
函数获取字符串长度
for _
in 1...amountToPad{
string = pad + string
}
return string
}
let originalString =
"hello"
let paddedString =
alignRight(originalString,
10, "_")
println("originalString: " +
originalString)
println("paddedString: " +
paddedString)
//_______________________________________________________________________________________________
//输入输出参数(变量参数仅仅在函数体内被更改,如果想要一个函数可以修改参数的值,并且想要在函数调用结束之后依旧存在,那么就应定义输入输出参数)
func swapTwoInts(inout a:
Int,
inout b: Int){
//使用 inout
函数来定义输入输出参数,输入输出参数不能有默认值,可变的参数不能用 inout
标记
let temp = a
a = b
b = temp
}
var someInt =
3
var anotherInt =
8
swapTwoInts(&someInt, &anotherInt)
//在调用函数时,当传入的参数作为输入输出参数的时候,在参数前加上 &
,表示这个值可以被函数修改
println("someInt is now
\(someInt), another is now
\(anotherInt)")
//***********************************************************************************************
//4.Function Types(函数类型)
//_______________________________________________________________________________________________
//函数类型的写法分为三步:1.定义函数; 2.声明函数类型变量或者常量; 3.给函数类型变量赋值
func addTwoInts(a:
Int, b: Int) ->
Int{ //定义函数
return a + b
}
var mathFunction: (Int,
Int) -> Int
//声明函数类型变量
mathFunction =
addTwoInts
//给函数类型变量赋值
println("result:
\(mathFunction(2,
3))")
//输出函数类型的变量
//_______________________________________________________________________________________________
//函数类型作为参数类型
func printMathResult(mathFun: (Int,
Int) -> Int, a:
Int, b: Int){
println("Result:
\(mathFun(a, b))")
}
printMathResult(mathFunction,
4, 7)
//_______________________________________________________________________________________________
//函数类型作为返回类型
func stepForward(input:
Int) -> Int{
return input + 1
}
func stepBackward(input:
Int) -> Int{
return input - 1
}
func chooseStepFunction(backward:
Bool) -> (Int) ->
Int{
//声明 chooseStepFunction
函数返回函数类型数据,返回类型为 (Int) -> Int
return backward ?
stepBackward: stepForward
//返回函数类型
}
var currentValue =
3
let moveNearerToZero =
chooseStepFunction(currentValue >
0)
//此时 moveNearerToZero
= stepBackward 函数
println("moveNearerToZero:
\(moveNearerToZero(10))")
//_______________________________________________________________________________________________
//嵌套函数
func chooseStepFunction1(backward:
Bool) -> ((Int) ->
Int){
func stepForward1(input:
Int) -> Int{
return input + 1
}
func stepBackward1(input:
Int) -> Int{
return input - 1
}
return backward ?
stepBackward1: stepForward1
//返回函数类型
}
var currentValue1 =
8
let moveNearerToZero1 =
chooseStepFunction1(currentValue >
0)
//此时 moveNearerToZero
= stepBackward 函数
println("moveNearerToZero:
\(moveNearerToZero1(10))")
相关文章推荐
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 08 Functions
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 10 Enumerations
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 24 Generics
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 09 Closures
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 11 Class and Structures
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 21 Nested Types
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 13 Methods
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 25 Listo's Conclusion
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 05 Strings and Characters
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 13 Methods
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 14 Subscripts
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 14 Subscripts
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 12 Properties
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 15 Inheritance
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 17 Deinitialization
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 01 About Swift
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 18 Automatic Reference Counting
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 18 Automatic Reference Counting
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 02 Swift Tour
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 16 Initialization