文档地址:

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 }

}

Swift3.1(6) Functions的更多相关文章

  1. HTML5 WebSocket实现点对点聊天的示例代码

    这篇文章主要介绍了HTML5 WebSocket实现点对点聊天的示例代码的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. ios – 在Swift的UIView中找到UILabel

    我正在尝试在我的UIViewControllers的超级视图中找到我的UILabels.这是我的代码:这是在Objective-C中推荐的方式,但是在Swift中我只得到UIViews和CALayer.我肯定在提供给这个方法的视图中有UILabel.我错过了什么?我的UIViewController中的调用:解决方法使用函数式编程概念可以更轻松地实现这一目标.

  3. ios – 在Swift中将输入字段字符串转换为Int

    所以我非常擅长制作APP广告Swift,我试图在文本字段中做一些非常简单的输入,取值,然后将它们用作Int进行某些计算.但是’vardistance’有些东西不正确它是导致错误的最后一行代码.它说致命错误:无法解开Optional.None解决方法在你的例子中,距离是一个Int?否则称为可选的Int..toInt()返回Int?因为从String到Int的转换可能失败.请参阅以下示例:

  4. 如何在iOS中检测文本(字符串)语言?

    例如,给定以下字符串:我想检测每个声明的字符串中使用的语言.让我们假设已实现函数的签名是:如果没有检测到语言,则返回可选字符串.因此,适当的结果将是:有一个简单的方法来实现它吗?

  5. xamarin – 崩溃在AccountStore.Create().保存(e.Account,“);

    在Xamarin.Forms示例TodoAwsAuth中https://developer.xamarin.com/guides/xamarin-forms/web-services/authentication/oauth/成功登录后,在aOnAuthenticationCompleted事件中,应用程序在尝试保存到Xamarin.Auth时崩溃错误说不能对钥匙串说期待着寻求帮助.解决方法看看你

  6. ios – 将视频分享到Facebook

    我正在编写一个简单的测试应用程序,用于将视频从iOS上传到Facebook.由于FacebookSDK的所有文档都在Objective-C中,因此我发现很难在线找到有关如何使用Swift执行此操作的示例/教程.到目前为止我有这个在我的UI上放置一个共享按钮,但它看起来已禁用,从我读到的这是因为没有内容设置,但我看不出这是怎么可能的.我的getVideoURL()函数返回一个NSURL,它肯定包含视

  7. xcode – 错误“线程1:断点2.1”

    我正在研究RESTAPI管理器.这是一个错误,我无法解决它.我得到的错误在下面突出显示.当我打电话给这个班级获取资源时:我评论的线打印:Thread1:breakpoint2.1我需要修复错误的建议.任何建议都非常感谢解决方法您可能在不注意的情况下意外设置了断点.单击并拖动代表断路器外部断点的蓝色刻度线以将其擦除.

  8. ios – 更改导航栏标题swift中的字符间距

    类型的值有人可以帮我这个或建议一种不同的方式来改变swift中导航栏标题中的字符间距吗?解决方法您无法直接设置属性字符串.你可以通过替换titleView来做一个技巧

  9. ios – 如何从变量访问属性或方法?

    是否可以使用变量作为Swift中方法或属性的名称来访问方法或属性?在PHP中,您可以使用$object->{$variable}.例如编辑:这是我正在使用的实际代码:解决方法你可以做到,但不能使用“纯粹的”Swift.Swift的重点是防止这种危险的动态属性访问.你必须使用Cocoa的Key-ValueCoding功能:非常方便,它完全穿过你要穿过的字符串到属性名称的桥,但要注意:这里是龙.

  10. ios – 如果我将自动释放的对象桥接到Core Foundation,我必须使用__bridge或__bridge_retained吗?

    ARC迁移工具遇到了这个问题:特别是,它不确定它是否应该执行__bridge或__bridge_retained.而我也是.-fileURLWithPath返回一个自动释放的对象,在这个地方我不是fileURL的所有者.但与此同时,该对象的保留计数至少为1.我敢打赌,这只能用__bridge来完成.解决方法您只想为此使用常规__bridge强制转换.仅当您想要管理强制转换CF对象的生命周期时,才会使用__bridge_retained.例如:所以__bridge_retained确实告诉编译器你有一个AR

随机推荐

  1. Swift UITextField,UITextView,UISegmentedControl,UISwitch

    下面我们通过一个demo来简单的实现下这些控件的功能.首先,我们拖将这几个控件拖到storyboard,并关联上相应的属性和动作.如图:关联上属性和动作后,看看实现的代码:

  2. swift UISlider,UIStepper

    我们用两个label来显示slider和stepper的值.再用张图片来显示改变stepper值的效果.首先,这三个控件需要全局变量声明如下然后,我们对所有的控件做个简单的布局:最后,当slider的值改变时,我们用一个label来显示值的变化,同样,用另一个label来显示stepper值的变化,并改变图片的大小:实现效果如下:

  3. preferredFontForTextStyle字体设置之更改

    即:

  4. Swift没有异常处理,遇到功能性错误怎么办?

    本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请发送邮件至dio@foxmail.com举报,一经查实,本站将立刻删除。

  5. 字典实战和UIKit初探

    ios中数组和字典的应用Applicationschedule类别子项类别名称优先级数据包contactsentertainment接触UIKit学习用Swift调用CocoaTouchimportUIKitletcolors=[]varbackView=UIView(frame:CGRectMake(0.0,0.0,320.0,CGFloat(colors.count*50)))backView

  6. swift语言IOS8开发战记21 Core Data2

    上一话中我们简单地介绍了一些coredata的基本知识,这一话我们通过编程来实现coredata的使用。还记得我们在coredata中定义的那个Model么,上面这段代码会加载这个Model。定义完方法之后,我们对coredata的准备都已经完成了。最后强调一点,coredata并不是数据库,它只是一个框架,协助我们进行数据库操作,它并不关心我们把数据存到哪里。

  7. swift语言IOS8开发战记22 Core Data3

    上一话我们定义了与coredata有关的变量和方法,做足了准备工作,这一话我们来试试能不能成功。首先打开上一话中生成的Info类,在其中引用头文件的地方添加一个@objc,不然后面会报错,我也不知道为什么。

  8. swift实战小程序1天气预报

    在有一定swift基础的情况下,让我们来做一些小程序练练手,今天来试试做一个简单地天气预报。然后在btnpressed方法中依旧增加loadWeather方法.在loadWeather方法中加上信息的显示语句:运行一下看看效果,如图:虽然显示出来了,但是我们的text是可编辑状态的,在storyboard中勾选Editable,再次运行:大功告成,而且现在每次单击按钮,就会重新请求天气情况,大家也来试试吧。

  9. 【iOS学习01】swift ? and !  的学习

    如果不初始化就会报错。

  10. swift语言IOS8开发战记23 Core Data4

    接着我们需要把我们的Rest类变成一个被coredata管理的类,点开Rest类,作如下修改:关键字@NSManaged的作用是与实体中对应的属性通信,BinaryData对应的类型是NSData,CoreData没有布尔属性,只能用0和1来区分。进行如下操作,输入类名:建立好之后因为我们之前写的代码有些地方并不适用于coredata,所以编译器会报错,现在来一一解决。

返回
顶部