Swift心得笔记之函数

2020-01-08 22:50:29丽君
函数是执行特定任务的代码自包含块。通过给定一个函数名称标识它是什么,并在需要的时候使用该名称来调用函数以执行任务。今天我们就来探讨下swift中的函数问题。  

参数

外部变量名

一般情况下你可以不指定外部变量名,直接调用函数:

 

复制代码
func helloWithName(name: String, age: Int, location: String) {
    println("Hello (name). I live in (location) too. When is your (age + 1)th birthday?")
}
helloWithName("Mr. Roboto", 5, "San Francisco")

 

但是在类 (或者结构、枚举) 中的时候,会自动分配外部变量名 (第一个除外) ,这时候如果还想直接调用就会报错了:

 

复制代码
class MyFunClass {  
    func helloWithName(name: String, age: Int, location: String) {
        println("Hello (name). I live in (location) too. When is your (age + 1)th birthday?")
    }
}
let myFunClass = MyFunClass()
myFunClass.helloWithName("Mr. Roboto", 5,  "San Francisco")

 

如果你怀念在 OC 中定义函数名的方式,可以继续这样定义,比如 helloWithName 这种,隐藏第一个函数的外部名:

 

复制代码
class MyFunClass {
    func helloWithName(name: String, age: Int, location: String) {
        println("Hello (name). I live in (location) too. When is your (age + 1)th birthday?")
    }
}
let myFunClass = MyFunClass()
myFunClass.helloWithName("Mr. Roboto", age: 5, location: "San Francisco")

 

如果你实在不想要外部变量名,那么可以用 _ 来代替:

 

复制代码
struct Celsius {
    var temperatureInCelsius: Double
    init(fromFahrenheit fahrenheit: Double) {
        temperatureInCelsius = (fahrenheit - 32.0) / 1.8
    }
    init(fromKelvin kelvin: Double) {