swift function example

Apple 教學:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

The function in the example below is called greet(person:), because that’s what it does—it takes a person’s name as input and returns a greeting for that person. To accomplish this, you define one input parameter—a String value called person—and a return type of String, which will contain a greeting for that person:

  1. func greet(person: String) -> String {
  2. let greeting = "Hello, " + person + "!"
  3. return greeting
  4. }

All of this information is rolled up into the function’s definition, which is prefixed with the func keyword. You indicate the function’s return type with the return arrow -> (a hyphen followed by a right angle bracket), which is followed by the name of the type to return.

The definition describes what the function does, what it expects to receive, and what it returns when it is done. The definition makes it easy for the function to be called unambiguously from elsewhere in your code:

  1. print(greet(person: "Anna"))
  2. // Prints "Hello, Anna!"
  3. print(greet(person: "Brian"))
  4. // Prints "Hello, Brian!"

相關文章

寫留言

你的電子郵件位址並不會被公開。 必要欄位標記為 *