- Swift 4 Programming Cookbook
- Keith Moon
- 336字
- 2021-07-08 10:21:23
How to do it...
Let's look at how functions are defined in Swift:
func nameOfFunction(parameterLabel1 parameter1: ParameterType1, parameterLabel2 parameter2: ParameterType2,...) -> OutputType {
// Function's implementaion
// If the function has an output type,
// the function must return a valid value
return output
}
Let's look at this in more detail to see how a function is defined:
- func : This indicates that you are declaring a function.
- nameOfFunction : This will be the name of your function, and by convention is written in camel case (this means that each word, apart from the first, is capitalized and all spaces are removed). This should describe what the function does, and should provide some context to the value returned by the function, if one is returned. This will be how you will invoke the method from elsewhere in your code, so bear that in mind when naming it.
- parameterLabel1 parameter1: ParameterType1 : This is the first input, or parameter, into the function. You can specify as many parameters as you like, separated by commas. Each parameter has a parameter name (parameter1) and type (ParameterType1); the parameter name is how the value of the parameter will be made available to your function's implementation. You can optionally provide a parameter label in front of the parameter name (parameterLabel1 ), which will be used to label the parameter when your function is used (at the call site).
- -> OutputType : This indicates that the function returns a value and indicates the type of that value. If no value will be returned, this can be omitted. In the following code illustration, the curly brackets indicate the start and end of the function's implementation; anything within them will be executed when the function is called:
{
// Function's implementaion
}
- return output : If the function returns a value, you type return and then the value to return. This ends the execution of the function; any code written after the return statement is not executed.
Now, let's put this into action.
推薦閱讀
- Object-Oriented JavaScript(Second Edition)
- Python:Master the Art of Design Patterns
- 可解釋機(jī)器學(xué)習(xí):模型、方法與實(shí)踐
- 微信小程序項(xiàng)目開(kāi)發(fā)實(shí)戰(zhàn)
- 前端HTML+CSS修煉之道(視頻同步+直播)
- Unity 2018 Augmented Reality Projects
- C陷阱與缺陷
- SSH框架企業(yè)級(jí)應(yīng)用實(shí)戰(zhàn)
- Continuous Delivery and DevOps:A Quickstart Guide Second Edition
- 數(shù)據(jù)科學(xué)中的實(shí)用統(tǒng)計(jì)學(xué)(第2版)
- Java Web動(dòng)態(tài)網(wǎng)站開(kāi)發(fā)(第2版·微課版)
- Java Web應(yīng)用開(kāi)發(fā)
- Java EE應(yīng)用開(kāi)發(fā)及實(shí)訓(xùn)
- VBA Automation for Excel 2019 Cookbook
- C#從入門(mén)到精通(第5版)