【问题标题】:An array of enum members using implicit member syntax使用隐式成员语法的枚举成员数组
【发布时间】:2021-06-05 13:34:58
【问题描述】:

考虑一下enum

enum FilmGenre: String, CaseIterable {
    case horror = "Horror"
    case comedy = "Comedy"
    case animation = "Animation"
    case romance = "Romance"
    case fantasy = "Fantasy"
    case adventure = "Adventure"
}

有没有办法这样写?

let filmGenres: [FilmGenre.RawValue] = [.horror.rawValue,
                                        .comedy.rawValue,
                                        .animation.rawValue]

编译器报错:

类型“FilmGenre.RawValue”(又名“字符串”)没有成员“恐怖”

我能做到的最好的就是这样。

let filmGenres: [FilmGenre.RawValue] = [FilmGenre.horror.rawValue,
                                        FilmGenre.comedy.rawValue,
                                        FilmGenre.animation.rawValue]

我已经尝试了自动完成的各种组合。

let filmGenres: [FilmGenre.AllCases.Element.RawValue] = [...]

Swift 5.4 中不能做到吗?

【问题讨论】:

  • 这个想法是将数组限制为 enum 成员原始值。不允许使用其他字符串值。我可以添加一个与enum 成员原始值完全无关的随机字符串。如果我把数组改成[String]注解,它可以是任何东西。

标签: arrays swift syntax enums


【解决方案1】:

[FilmGenre.RawValue] 在这种情况下转换为[String],显然String 不知道在其他类型FilmGenre 中定义的.horror

你能做的是-

enum FilmGenre: String, CaseIterable {
    case horror = "Horror"
    case comedy = "Comedy"
    case animation = "Animation"
    case romance = "Romance"
    case fantasy = "Fantasy"
    case adventure = "Adventure"
}

/// Have a variable that is of `[FilmGenre]` type
/// This will allow you to use the type safety you are looking for
let filmGenres: [FilmGenre] = [.horror, .comedy, .animation]

/// This one you can use anywhere else as you like
/// This will give you `[String]` which is what you want in this case
let filmGenreRawValues = filmGenres.map({ $0.rawValue })

【讨论】:

    【解决方案2】:

    您可以将带有 var args 的静态函数添加到您的枚举中,以获得更动态的方式来创建数组

    static func arrayWithRawValues(_ genre: FilmGenre...) -> [Self.RawValue] {
        genre.map(\.rawValue)
     }
    

    例子

    print(FilmGenre.arrayWithRawValues(.horror, .comedy, .animation))
    

    输出

    [“恐怖”、“喜剧”、“动画”]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 2018-11-05
      • 1970-01-01
      相关资源
      最近更新 更多