【发布时间】: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]注解,它可以是任何东西。