无法使用默认值初始化结构 [英] Can't initialize a struct with a default value
问题描述
struct Struct1 {
let myLet = "my let"
let myLet2: Bool
let myLet3: String
}
let s1 = Struct1(myLet2: false, myLet3: "My url123")
错误是:缺少参数myLet
的参数.这是为什么?它具有默认值.
The error is: missing argument for parameter myLet
. Why is that? It has a default value.
推荐答案
Swift 5.1 :
标记为var
的变量在构造函数中是可选的,并且将使用其默认值.示例:
Variables, marked with var
are optional in constructors and their default value will be used. Example:
struct Struct {
var param1: Int = 0
let param2: Bool
}
let s1 = Struct(param2: false) // param1 = 0, param2 = false
let s2 = Struct(param1: 1, param2: true) // param1 = 1, param2 = true
对于 Swift的旧版本(< 5.1):
对于Struct,默认初始化是全部或全部为空.您可以为所有属性定义默认值,然后获得自动生成的初始化程序Struct1()
以及具有所有属性的初始化程序,或者仅获得具有所有属性的初始化程序,包括碰巧具有默认值的任何属性.您将必须实现自定义初始化程序.
Default Initialization is all-or nothing for a Struct. Either you define defaults for all properties and you get an automatically generated initializer Struct1()
plus an initializer with all of the properties, or you get only the initializer with all of the properties, including any that happen to have a set default value. You're going to have to implement a custom initializer.
struct Struct1 {
let myLet = "my let"
let myLet2: Bool
let myLet3: String
init(myLet2: Bool, myLet3: String) {
self.myLet2 = myLet2
self.myLet3 = myLet3
}
}
这篇关于无法使用默认值初始化结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!