最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]Swift中的delegate中的函数如何定义和实现

Swift crifan 2642浏览 0评论

[背景]

折腾:

[已解决]如何把Object-C中的protocol和delegate转为Swift代码

期间,看到之前OC代码:

- (BOOL)mh_tabBarController:(MHTabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController atIndex:(NSUInteger)index;
- (void)mh_tabBarController:(MHTabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController atIndex:(NSUInteger)index;

 

和官网的:

protocol DiceGameDelegate {
。。。
    func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)
。。。
}

看着函数定义就很复杂,看不太懂到底是如何定义的。

需要去搞懂,到底如何定义的。

 

[解决过程]

1.搜:

swift function definition

参考:

The Swift Programming Language (Swift 2): Functions

去看看那个:

Function Parameter Names

 

[总结]

函数参数名,有两个名字:

外部参数名称:用于标识外部传入的参数。默认情况下,第一个参数会忽略掉外部参数名。

内部参数名称:用于内部函数实现时候用到的变量

默认情况下:

第一个参数:会忽略掉外部参数名:

第二个及其余的参数:默认会使用内部参数名,作为外部参数名。

尽管对于多参数来说,是允许有相同的外部参数名的,但是所有参数都必须有独一无二的内部参数名。而外部参数名不同有利于提高代码可读性。

 

举例:

func someFunction(externalParameterName localParameterName: Int) {
    // function body goes here, and can use localParameterName
    // to refer to the argument value for that parameter
}

如果你给参数设置了外部参数名,那么你调用函数的时候,就必须提供对应的外部参数名。

 

举例:

func sayHello(to person: String, and anotherPerson: String) -> String {
    return "Hello \(person) and \(anotherPerson)!"
}
print(sayHello(to: "Bill", and: "Ted"))
// prints "Hello Bill and Ted!"

 

-》

Swift设计了外部参数名的目的是:

使得代码写出来,更加易懂,已读-》单独看代码,就容易看懂,代码本身的含义,所要干的事情是什么

-》比如上面的代码:

print(sayHello(to: "Bill", and: "Ted"))

就容易被解读为:向 bill 和 ted 说hello

而如果,不带函数的外部参数,则函数调用是这样的:

print(sayHello("Bill", "Ted"))

则此时,你就没法判断,本身这句话的大概含义是什么:

因为有可能是,sayHello函数本书内部所要实现的功能实际上是:

先和(第一个参数的)bill说hello,再和(第二个参数的)ted说hello

也可能是:

先和(第二个参数的)ted说hello,再和(第一个参数的)bill说hello

还可能是:

同时和bill和ted说hello

 

如果不想要使用外部函数参数名,则可以用下划线_去忽略掉:

func someFunction(firstParameterName: Int, _ secondParameterName: Int) {
    // function body goes here
    // firstParameterName and secondParameterName refer to
    // the argument values for the first and second parameters
}
someFunction(1, 2)

至此,算是对于函数参数,有了更深入的了解了。

至少对于:

func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)

这种,算是可以看懂了:

didStartNewTurnWithDiceRoll diceRoll: Int

是第二个参数

其中的didStartNewTurnWithDiceRoll是外部参数名, diceRoll是内部参数名。

转载请注明:在路上 » [已解决]Swift中的delegate中的函数如何定义和实现

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.180 seconds, using 22.03MB memory