Swift 4 custom argument labels - required? [closed]

若如初见. 提交于 2019-12-27 06:03:30

问题


func greet (person person: String, on day: String) -> String {
    return "Hello \(person) on \(day)"
}

can be executed as

greet ("John", "23")

Swift 4 - custom argument labels behave as no argument label - "_".

How to make custom labels mandatory for execution?

greet (person: "John", on: "23")

Thanks.

Edit - question is incorrect, as custom labels are mandatory


回答1:


In Swift each function parameter can have both argument label and a parameter name.

  1. argument label: used in function call
  2. parameter name: used inside the function definition

By default, parameters use their parameter name as their argument label.

These are the possible function declarations that can be used in swift:

Case 1: parameter name is same as the argument label

func greet (person: String, day: String) -> String {
    return "Hello \(person) on \(day)"
}

Function Call: greet(person: "John", day: "23")

Case 2: different parameter name and argument label

func greet (person person: String, on day: String) -> String {
    return "Hello \(person) on \(day)"
}

Function Call: greet(person: "John", on: "23")

Case 3: using _ as argument label

func greet (_ person: String, _ day: String) -> String {
    return "Hello \(person) on \(day)"
}

Function Call: greet("John", "23")

For more on how function parameters work, you can refer to: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

Let me know if you still face any issues.



来源:https://stackoverflow.com/questions/49349247/swift-4-custom-argument-labels-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!