Swift - 如何用枚举字典初始化变量?

Swift - how to initialize variable with dictionary of Enum?

我对枚举和初始化它们有点困惑。

代码如下:

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

这里的'waves'是什么?它是 'WaveType' 枚举的 array/dictionary 吗?如果是这样,你能解释一下 waves[.far] = addWave()durations[.far] = 4 吗?为什么我认为它应该像 waves = [.far : addWave()]durations = [.far : 4]

如果太明显请见谅,谢谢

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

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

Right now, since you are using a dictionary, what you've built can only handle 2 waves: a close wave, and a far wave. I'm thinking that you might want more than 2 waves? Maybe 5 close waves?

从字典迁移到数组后,您的代码如下所示:

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
)]

不过,如您所说,这感觉有点笨拙:

wondering how can I make addWave function shorter ? As it [has a lot of parameters]

具体说明这些参数:

  • 位置:CGPoint
  • z位置:CGFloat
  • xScale: CGFloat
  • 方向:WaveDirection

我认为它可以缩短,我建议可以分 3 个步骤完成。


第 1 步

让我们编辑您的 WaveNode class 以包含 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. 我在每个参数标记前添加了下划线 _decrease length when calling the method
  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(...))

如果你想要更短的方法来重写这个,我很乐意帮忙。让我知道你的想法。