简体   繁体   English

Swift:swift 访问 function 在结构无 init

[英]Swift: swift access function in struct no init

I'm trying to access to function in struct like this我正在尝试以这样的结构访问 function

struct DoSomething {
    var str: String

    func processNumber(number: Int) -> String {
        return "\(number)"
    }
}

let number = DoSomething().processNumber(number: 10)
print(number)

But I'm getting this error:但我收到了这个错误:

Missing argument for parameter 'str' in call

Any of you knows how can Access the function in the struct.你们中的任何人都知道如何访问结构中的 function。

I'll really appreciate your help.我会非常感谢你的帮助。

You should pass a paramter like this be你应该像这样传递一个参数

let number = DoSomething(str:"someValue").processNumber(number: 10)

As there is no () init in that case, if you need it a separate logic do由于在这种情况下没有() init,如果你需要它一个单独的逻辑做

class func processNumber(number: Int) -> String {
    return "\(number)"
}

and call like并打电话给

let number = DoSomething.processNumber(number: 10)

note if the var var str: String has no usage you should not create it either请注意,如果 var var str: String没有使用,您也不应该创建它

You have to initialize str when creating an instance of DoSomething .创建DoSomething的实例时,您必须初始化str

Either assign a default value in the struct在结构中分配一个默认值

struct DoSomething {

    var str: String = ""

    ....

}

let number = DoSomething().processNumber(number: 10)

Or in the initializer which has the signature init(str: String)或者在具有签名init(str: String)的初始化程序中

let number = DoSomething(str: "").processNumber(number: 10)

The issue can be resolved by declaring the str as an optional.可以通过将str声明为可选项来解决此问题。

struct DoSomething {
    var str: String?

    func processNumber(number: Int) -> String {
        return "\(number)"
    }
}

let number = DoSomething().processNumber(number: 10)
print(number)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM