Swift3.1(6) Functions

前端之家收集整理的这篇文章主要介绍了Swift3.1(6) Functions前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

文档地址:

https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html#//apple_ref/doc/uid/TP40014097-CH10-ID158

1Swift’s unified function Syntax is flexible enough to express anything from a simple C-style function with no parameter names to a complex Objective-C-style method with names and argument labels for each parameter

swift 联合的函数语法是足够地复杂能表达从一个没有参数名字简单的c风格的函数到一个复杂的oc 风格对每一个参数有名字和参数标签方法

2Function parameters and return values are extremely flexible in Swift.

在swift里面函数的参数以及返回类型都是非常灵活的

3、functions are not required to define inout parameters.

func sayHelloWorld() -> String {

return “Hello,world”

}

//尽管没有参数,后面扔需要括号

with parameter:

func greetAgain(person: String) -> String {

return “Hello again,” + person + “!“

}

4、func greet (person :String,alreadyGreeted: Bool) -> String {

}

multiple Parameters

5、func greet (person : String) {

print (“Hellp,\(perosn)!”)

}

functions without return value没有返回值的类型函数,因为不需要返回值这里就不需要一个return arrow 和返回的类型。

6、Strictly speaking,this version of the greet(perosn:) function does still return a value,even though no return value is defied.Functions without a defined return type return a special value of type Void.This is simply an empty tuple,which is written as ().

严格的说,这个版本的函数扔返回一个值,即使没有值被定义。没有被定义一个返回类型的函数会返回一个Void类型的值。这是一个简单的tuple值,写成()。

7、The return value of a function can be ignored when it is called .一个函数调用的时候的返回类型能被忽视。

8、func printAndCount(string: String) -> Int {

print(string)

return string.characters.count

}

call: printAndCount(string: “hello,world”)

9、Return values can be ignored,but a function that says it will return a value must always do so.A function with a defined return type cannot allow control to fall out of the bottom of the function without returning a value,and attempting to do so will result in a compile-time error.

返回值能被忽略,但是一个说它将返回一个值的函数就必须返回一个值,一个定义了返回类型的函数如果没有返回一个值,那么它将不允许这个控制流走出函数底部,如果尝试这么做将会导致一个编译时间错误

10、functions with Multiple Return Values

拥有多个返回值的函数

You can use a tuple type as the return type for a function to return multiple values as part of one compound return value .

你能应用一个tuple类型作为一个函数的返回值来返回多个值,这些值作为符合返回值的一部分。

func minMax(array: [Int]) -> (min:Int,max: Int) {

var currentMin = array[0]

var currentMax = array[0]

for valuein array[1..<array.count] {

if value < currentMin {

currentMin = value

}elseif value > currentMax {

currentMax = value

}

}

return (currentMin,currentMax)

}

Finally,the overall mininum and maximum values are returned as a tuple of two Int values.最后全体里面最大的或者最小的以两个整数的元组返回。

let bounds = mixMax(array: [8,-6,2,109,3,71])

print (“min is \(bounds.min) and max is \(bounds.max)”)

11Optional Tuple Return Types

An optional tuple type such as (Int,Int)? is different from a tuple that contains optional types such as (Int?,Int?).With an optional tuple type,the entire tuple is optional,not just each individual value within the tuple.

一个选择性的元组跟包含选择性元素的元组不一样,对于一个选择性的元组类型,整个元组都是选择性的,不仅仅是元组里面的个体元素。

12、Function Argument Labels and Parameter

Each function parameter has both an argument label and a parameter name .The argument label is used when calling the function;each argument is written in the function call with its argument label before it .The parameter name is used in the implementation of the function.By default,parameters use their parameter name as their argument label.

每个函数都有一个参数标签和一个参数名字。当使用函数的时候参数标签被使用,每个参数写在参数标签的前面,参数名字用在功能的实现,默认,参数用参数名字作为他们参数的标签

func someFunciton(firstParameterName: Int,secondParameterName: Int) {

//boby 里面的参数firstParameterName和secondParameterName能用

}

someFunction(firstParameterName:1,secondParameterName:2)

函数调用的时候使用

13、函数参数名必须不同

14、you write an argument label before the parameter name,sepatated by a space.

你可以在参数名字前加一个参数的标签,用一个空格分开。

func greet(person: String,from hometowm: String) -> String {

}

然后你可以这么来调

print(greet(person: “Bill”,from: “Cupertino”))

15、if you don’t want an argument label for a parameter,write an underscore (_)instead of an explicit argument label for that parameter.

如果你不想在一个参数前写一个参数标签,写一个(_)为那个参数代替一个参数标签

func someFunction(_ firstParameterName: Int,secondParameterName: Int) {

}

someFunction(1,secondParameterName: 2)

但是如果有的话,就一定要加上

16、Default Parameter Values默认参数值

如果一个默认值被设置了,当调函数的时候你能省略那个参数。

func someFunction(paramterWithoutDefault: Int,parameterWithDefault: Int = 12) {

}

除非我们主动设定这个默认值,不然那个参数就是12,

someFunction(parameterWithoutDefault: 3,parameterWithDefault: 6) {

}//parameterWithDefault is 6

someFunction(parameterWithoutDefault: 4) 省略后那个值就是12

非默认值一般写在前面

17、Variadic Parameters可变参数

The values passed to a variadic parameter are made available within the function’s boby as an array of th e appropriate type.

那些传进去可变参数的值是有效的,在函数的body里作为一个数组

func arithmeticMean(_ numbers: Double…) -> Double {

var total: Double = 0

for number in numbers {

total += number

}

return total / Double(numbers.count)

}

函数里面最多有一个可变参数

18、

(1)If you want a function to modify a parameter’s value,and you want those changes to persist after the function call has ended,define that parameter as an in-out parameter instead.

这样声明是用来修改参数的值

(2)An in-out parameter has value that is passed in to the function,is modified by the function,and is passed back out of the function to replace the original value.

一个in-out 参数传进函数体里面,能被函数修改,然后被传出函数的外面来代替几个原始的值。

(3)you can only pass a variable as the argument for an in-out parameter.

你只能传一个变量作为一个in-out 参数

(4)You place an ampersand(&)directly before a variable’s name when you pass it as an argument to an in-out parameter,to indicate that it can be modified by the function.

你放置一个&符号在一个变量的前面,当你把它作为一个参数传递进in-out 参数时,显示它是可以被修改的。

var someInt = 3

var anotherInt = 107

swapTwoInts(&someInt,&anotherInt)

print (“someInt is now \(someInt),and anotherInt is now \(anotherInt)”)

//Prints “someInt is now 107,and antherInt is now 3”

通过这样的处理,把值换了,即使变量在外面

(5)In-out parameters are an alternative way for a function to have an effect outside of the scope of its function body.

in-out 参数是一种可选的方式,能影响它的函数体外边的范围

19、FunctionTypes 函数的类型

func addTwoInts(_ a: Int,_b: Int) -> Int {

return a +b;

}

function type :(Int,Int) -> Int

func printHellWorld() {

print(“Hello,world”)

}

function type : () -> Void

20、You use funciton types just like any other types in Swift.


var mathFuction: (Int,Int) -> Int = addTwoInts

you can define a constant or variable to be of a function type and assign an appropriate function to that variable.

我们可以将一个函数类型的变量赋值发给另一个变量

因为addTwoInts 和mathFunction 有相同的变量类型,这种赋值是允许的。

A different function with the same matching type can be assigned to the same varible,in the same way as for non-function types:

一个不同的函数有相同的类型能被赋值给相同的变量,就像非函数类型变量一样。

21、function types as Parameter types

函数类型作为参数变量

func printMathResult(_ mathFunction: (Int,Int ) -> Int,_a: Int,_ b: Int) {

print(“Result: \(mathFunction(a,b))”)

}

printMathResult(addTwoInts,5)

printMathRestult 不管addTwoInts的实现是什么,它只对这类型进行限制,确保函数调用以一种类型安全的方式调用

22、function types as return types

func stepForward(_ input:Int) -> Int {

return input +1

}

func stepBackward(_ input:Int) -> Int {

return input -1

}

func chooseStepFunction(backWard:Bool) -> (Int) ->Int {

return backWard ? stepBackward :stepForward

}

var currentValue =3

let moveNearerToZero =chooseStepFunction(backWard: currentValue >0)

print("moveNearerToZero value is\(moveNearerToZero)")

23Nested Functions嵌套函数

与global functions相反,上面所有的都是全局的。

You can also define functions inside the bodies of other functions,known as nested functions

你也能在函数的内部定义其他的函数,就是嵌套函数

An enclosing function can also return one of its nested functions to allow the nested function to be used in another scope.

一个封闭的函数能返回他的一个嵌套函数,这个函数能被用在另一个范围。

func chooseStepFunction(backwark: Bool) -> (Int) -> Int {

func stepForward(input: Int) -> Int { return input + 1}

func stepbackward(input :Int) -> Int ( return input -1 }

}

猜你在找的Swift相关文章