实际上,以上答案确实很棒,但它们却缺少一些细节,这些细节是持续开发的客户端/服务器项目中许多人需要的。我们在开发应用程序的同时,后端会随着时间的推移不断发展,这意味着某些枚举案例将改变这种发展。因此,我们需要一种枚举解码策略,该策略能够解码包含未知情况的枚举数组。否则,解码包含数组的对象将完全失败。
我所做的很简单:
enum Direction: String, Decodable {
case north, south, east, west
}
struct DirectionList {
let directions: [Direction]
}
extension DirectionList: Decodable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
var directions: [Direction] = []
while !container.isAtEnd {
// Here we just decode the string from the JSON which always works as long as the array element is a string
let rawValue = try container.decode(String.self)
guard let direction = Direction(rawValue: rawValue) else {
// Unknown enum value found - ignore, print error to console or log error to analytics service so you'll always know that there are apps out which cannot decode enum cases!
continue
}
// Add all known enum cases to the list of directions
directions.append(direction)
}
self.directions = directions
}
}
奖励:隐藏实现>使其成为集合
隐藏实现细节始终是一个好主意。为此,您只需要多一点代码。关键是要符合DirectionsList
以Collection
使您的内部list
阵列私人:
struct DirectionList {
typealias ArrayType = [Direction]
private let directions: ArrayType
}
extension DirectionList: Collection {
typealias Index = ArrayType.Index
typealias Element = ArrayType.Element
// The upper and lower bounds of the collection, used in iterations
var startIndex: Index { return directions.startIndex }
var endIndex: Index { return directions.endIndex }
// Required subscript, based on a dictionary index
subscript(index: Index) -> Element {
get { return directions[index] }
}
// Method that returns the next index when iterating
func index(after i: Index) -> Index {
return directions.index(after: i)
}
}
您可以在John Sundell的此博客文章中了解有关符合自定义集合的更多信息:https ://medium.com/@johnsundell/creating-custom-collections-in-swift-a344e25d0bb0