首页 > 解决方案 > 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]

如果太明显了,对不起,谢谢。

标签: swiftdictionaryenumsinitialization

解决方案


我们在评论中讨论的内容:

就个人而言,我会将字典更改为数组。正如我之前所说:

现在,由于您使用的是字典,因此您构建的内容只能处理 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 个新属性:waveTypeduration. 正如 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()方法。我以两种方式对其进行了编辑:

  1. 在调用方法时,_我在每个参数标记前添加了下划线以减少长度。
  2. 我将waveTypeduration作为参数添加到您的方法中,如下所示:
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 步

添加waveTypeduration作为属性WaveNode让我们不必再使用元组数组。相反,它看起来像这样:

var waves = [WaveNode]()

// And adding waves will be easy and much shorter:
waves.append(waveNode(...))

如果您想要更短的方法来重写它,我很乐意提供帮助。让我知道你的想法。


推荐阅读