如何创建 Swift 函数(或 class)并传递一些变量

How to create a Swift function (or class) and pass some variables

在PHP中,我习惯创建这样一个函数

function fun ($one,$two) { return $two; }

稍后我可以在 PHP 做

$variable1 = "something";
$variable2 = "something2";
echo fun($variable1,$variable2);

但我是 Xcode / Swift 5

的新手

我创建了一个class

class APIX {
    
    var urlxtra: String
    var deviceToken: String
       
    init(urlxtra: String, deviceToken: String) {
        
        self.urlxtra = urlxtra
        self.deviceToken = deviceToken
        
        let url = "https://www.api__url___.com/v1/"+deviceToken+"/"+urlxtra+"/"
        
        let urlObj = URL(string: url)
        var urlRequest = URLRequest(url: urlObj!)
        
        urlRequest.httpMethod = "GET"
        urlRequest.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
        
        let task = URLSession.shared.dataTask(with: urlObj!)
        
        task.resume()
        
    }
}

并这样称呼它有效

let apicall = APIX(urlxtra: "somthing1", deviceToken: "something2")

但是当我这样做的时候

let stubToken = "somthing3";
let apicall = APIX(urlxtra: "somthing1", deviceToken: stubToken)

Xcode 说:

Cannot use instance member 'stubToken' within property initializer; property initializers run before 'self' is available

我该如何解决这个问题?

几种可能的解决方案

声明为lazy

let stubToken = "somthing3";
lazy var apicall = APIX(urlxtra: "somthing1", deviceToken: stubToken)

或者用init方法初始化它

let stubToken = "somthing3";
let apicall: APIX

init() {
    apicall = APIX(urlxtra: "somthing1", deviceToken: stubToken)
}

或者如果变量可以更改,则将它们传递给 init 方法

let apicall: APIX

init(urlxtra: String, stubToken: String) {
    apicall = APIX(urlxtra: urlxtra, deviceToken: stubToken)
}

我猜你做了这样的事情:

class Something {

    let stubToken = "somthing3";
    let apicall = APIX(urlxtra: "somthing1", deviceToken: stubToken)
}

两者都是实例属性,同时初始化(不保证它们的初始化顺序),因此不能依赖另一个。您需要建立依赖关系,以便 stubTokenapicall.

之前初始化

如果stubToken真的是一个常量,让它成为静态的:

class Something {

    static let stubToken = "somthing3";
    let apicall = APIX(urlxtra: "somthing1", deviceToken: Something.stubToken)
}

如果它是一个变量,你可以在 init 中初始化 apicall 它,或者像其他答案建议的那样使第二个变量 lazy