我收到一个错误,表示“丢失参数标签”日期:“在通话”根据这个屏幕截图:
这是代码: –
import Foundation import UIKit class ViewController2: UIViewController { override func viewDidLoad() { super.viewDidLoad() //var dailyStatement = greet("John","Tuesday") var dailyStatement = greet("John",day: "Tuesday") println(dailyStatement) } func greet(name: String,day: String) -> String { return "Hello \(name),today is \(day)." } }
经过一些研究,我发现这个帖子:Difference between a method and a function,在我看来,我在一个类中声明的函数实际上被称为一个方法。所以我用来调用该方法的语法与我用来调用函数的语法不同。
当我在Objective-C中编程时,我从来没有意识到这种差异。
Swift中的功能
Functions are self-contained chunks of code that perform a specific
task. You give a function a name that identifies what it does,and
this name is used to “call” the function to perform its task when
needed.
资源:Official Apple Documentation on Functions in Swift
However,these parameter names are only used within the body of the
function itself,and cannot be used when calling the function. These
kinds of parameter names are known as local parameter names,because
they are only available for use within the function’s body.
这意味着默认情况下,Function的所有参数都是本地参数。
但是,有时我们想要指出每个参数的目的。所以我们可以为每个参数定义一个外部参数名称。代码示例:
func someFunction(externalParameterName localParameterName: Int) { // function body goes here,and can use localParameterName // to refer to the argument value for that parameter }
func someFunction(#localParameterName: Int) { // function body goes here,and can use localParameterName // to refer to the argument value for that parameter }
someFunction(localParameterName:10)
Swift方法
Methods are functions that are associated with a particular type.
Classes,structures,and enumerations can all define instance methods,
which encapsulate specific tasks and functionality for working with an
instance of a given type.
资源:Official Apple Documentation on Methods in Swift
However,the default behavior of local names and external names is
different for functions and methods.Specifically,Swift gives the first parameter name in a method a local
parameter name by default,and gives the second and subsequent
parameter names both local and external parameter names by default.
import Foundation import UIKit class ViewController2: UIViewController { override func viewDidLoad() { super.viewDidLoad() //Default methods calling var dailyStatement = greet("Rick",day: "Tuesday") println(dailyStatement) //First parameter is also an external parameter var dailyStatement2 = greet2(name:"John",day: "Sunday") println(dailyStatement2) } //Default: First Parameter is the local parameter,the rest are external parameters func greet (name: String,today is \(day)." } //Use Hash symbol to make the First parameter as external parameter func greet2 (#name: String,today is \(day)." } }
我可能会想念一些重要的细节。希望有人能提供更好的答案。