swift - Swift - 如何使用枚举字典初始化变量?
问题描述
我对枚举和初始化它们有点困惑。
这是代码:
enum WaveType {
case close
case far
}
class WaveNode: SKNode {
...
}
func addWave() -> WaveNode {
let wave = WaveNode()
...
return wave
}
var waves = [WaveType: WaveNode]()
waves[.far] = addWave()
var durations = [WaveType: TimeInterval]()
durations[.far] = 4
这里的“波浪”是什么?它是“WaveType”枚举的数组/字典吗?waves[.far] = addWave()
如果是这样,你能解释一下durations[.far] = 4
吗?为什么我认为它应该类似于waves = [.far : addWave()]
或durations = [.far : 4]
如果太明显了,对不起,谢谢。
解决方案
我们在评论中讨论的内容:
就个人而言,我会将字典更改为数组。正如我之前所说:
现在,由于您使用的是字典,因此您构建的内容只能处理 2 波:近波和远波。我在想你可能想要超过 2 波?也许5个近波?
这是您的代码从字典迁移到数组后的样子:
enum WaveType { case close, far }
class WaveNode: SKNode {}
func addWave() -> WaveNode {}
// I have taken the initiative to group these up into a tuple:
var waves = [(waveType: WaveType, waveNode: WaveNode, duration: TimeInterval)]()
// Here's what adding a wave to the list would look like:
waves.append((waveType: .far, waveNode: addWave(...), duration: 4))
// Here's an alternate but identical way to add a wave to your array:
waves += [(
waveType: .far,
waveNode: addWave(...),
duration: 4
)]
不过,正如您所说,这感觉有点笨拙:
想知道如何使
addWave
功能更短?因为它[有很多参数]
具体来说,您声明了这些参数:
- 位置:CGPoint
- zPosition: CGFloat
- xScale: CGFloat
- 方向:波方向
我认为它可以做得更短,我建议这可以分 3 步完成。
步骤1
让我们编辑您的WaveNode
类以包含 2 个新属性:waveType
和duration
. 正如 position、zPosition、xScale 和 direction 都是WaveNode
.
class WaveNode: SKNode {
// include these, as well as some default value
var duration: TimeInterval = 0
var waveType = .far
}
第2步
接下来,我们将编辑您的addWave()
方法。我以两种方式对其进行了编辑:
- 在调用方法时,
_
我在每个参数标记前添加了下划线以减少长度。 - 我将
waveType
和duration
作为参数添加到您的方法中,如下所示:
func addWave(_ position: CGPoint,_ zPosition: CGFloat,_ xScale: CGFloat,_ direction: WaveDirection,_ waveType: WaveType,_ duration: TimeInterval) -> WaveNode {
let wave = WaveNode()
// Keep all code that was in between
// Just add these 2 lines above the return line
wave.waveType = waveType
wave.duration = duration
return wave
}
第 3 步
添加waveType
和duration
作为属性WaveNode
让我们不必再使用元组数组。相反,它看起来像这样:
var waves = [WaveNode]()
// And adding waves will be easy and much shorter:
waves.append(waveNode(...))
如果您想要更短的方法来重写它,我很乐意提供帮助。让我知道你的想法。
推荐阅读
- javascript - 将 font-face 与 webpack encore 一起使用
- c# - Monogame C#:如何创建一个固定的图像网格,使其均匀地适合每个单元格?
- unity3d - 无法在 HoloLens 上部署
- angular - 从服务类进行嵌套 HTTP 调用并返回 Observable
- unit-testing - Nsubstitute 不能用 in 参数模拟带有签名的接口
- reactjs - 如何根据使用 React 的路由更改单独标题组件上的页面标题?
- jquery - inIframe 函数说明
- javascript - JavaScript TypeError:无法读取未定义的属性“id”
- javascript - 将所选语言保存在本地存储中?
- python - 多单元格的值错误问题尺寸必须相等,但为 20 和 13