您编写box()。试试这个:var A1Box = Box()
,
您的代码中有一些错误。
- 案例很重要。使用
Box
,而不是box
。
- 类必须具有一个初始化程序(一个结构体应为您创建一个初始化器)
- 初始化实例时,必须初始化类/结构的所有非可选属性
结构可能更适合您的模型:
struct PhysUnit {
var Mean: Double = 0.0
var Sigma: Double = 0.0
}
struct Box {
var Name: String?
var Width: PhysUnit
var Depth: PhysUnit
var Height: PhysUnit
}
func setupShelves() {
var A1Box = Box(Name: "A1",Width: PhysUnit(Mean: 40,Sigma: 0.5),Depth: PhysUnit(),Height: PhysUnit())
shelves.append(A1Box)
}
但是如果您坚持使用类,则可以执行以下操作:
struct PhysUnit {
var Mean: Double = 0.0
var Sigma: Double = 0.0
}
class Box {
var Name: String?
var Width: PhysUnit
var Depth: PhysUnit
var Height: PhysUnit
init(Name: String?,Width: PhysUnit,Depth: PhysUnit,Height: PhysUnit) {
self.Name = Name
self.Width = Width
self.Depth = Depth
self.Height = Height
}
}
func setupShelves() {
var A1Box = Box(Name: "A1",Height: PhysUnit())
shelves.append(A1Box)
}
,
快速解答:
struct PhysUnit {
var mean: Double = 0.0
var sigma: Double = 0.0
}
class Box {
var name: String = "null"
var width: PhysUnit = PhysUnit()
var depth: PhysUnit?
var height: PhysUnit?
init() {}
}
func setupShelves() {
var A1Box = Box()
A1Box.name = "A1"
A1Box.width.mean = 40.0
A1Box.width.sigma = 0.5
...
shelves.append(A1Box)
}
几件事:
- 您需要初始化所有变量或将其设置为可选(
是我所做的)
- 由于
PhysUnit
具有默认值,因此您不需要
将其设置为var width
的默认值。
编辑说明:我还更改了大小写,以匹配Swift最佳实践
,
首先请遵守命名约定,即变量名以小写字母开头。
优良作法是使用默认值编写初始化程序,而不是直接将其分配给属性
struct PhysUnit {
var mean: Double
var sigma: Double
init(mean : Double = 0.0,sigma: Double = 0.0) {
self.mean = mean
self.sigma = sigma
}
}
class Box {
var name : String
var width : PhysUnit
var depth : PhysUnit
var height : PhysUnit
init(name : String,width : PhysUnit = PhysUnit(),depth : PhysUnit = PhysUnit(),height : PhysUnit = PhysUnit()) {
self.name = name
self.width = width
self.depth = depth
self.height = height
}
}
func setupShelves() {
let a1Box = Box(name: "A1",width: PhysUnit(mean: 40.0,sigma: 0.5))
shelves.append(a1Box)
}
,
你在这里...
struct PhysUnit {
var Mean: Double = 0.0
var Sigma: Double = 0.0
}
class Box {
var Name: String?
var Width = PhysUnit()
var Depth: PhysUnit?
var Height: PhysUnit?
}
func setupShelves() {
var A1Box = Box()
A1Box.Name = "A1"
A1Box.Width.Mean = 40.0
A1Box.Width.Sigma = 0.5
}
这里的代码有很多问题。如果您做过Swift教程,可能会有所帮助。
这可能会有所帮助:https://www.youtube.com/watch?v=Ulp1Kimblg0
本文链接:https://www.f2er.com/3165420.html