Trên thực tế, các câu trả lời ở trên thực sự rất hay, nhưng chúng thiếu một số chi tiết cho những gì nhiều người cần trong một dự án máy khách / máy chủ được phát triển liên tục. Chúng tôi phát triển một ứng dụng trong khi phần phụ trợ của chúng tôi liên tục phát triển theo thời gian, điều đó có nghĩa là một số trường hợp enum sẽ thay đổi sự tiến hóa đó. Vì vậy, chúng ta cần một chiến lược giải mã enum có thể giải mã các mảng của enum có chứa các trường hợp không xác định. Mặt khác, giải mã đối tượng chứa mảng đơn giản là thất bại.
Những gì tôi đã làm khá đơn giản:
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
}
}
Phần thưởng: Ẩn thực hiện> Biến nó thành Bộ sưu tập
Để ẩn chi tiết thực hiện luôn là một ý tưởng tốt. Đối với điều này, bạn sẽ cần thêm một chút mã. Bí quyết là để phù hợp DirectionsList
với Collection
và làm cho nội bộ của bạn list
mảng tin:
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)
}
}
Bạn có thể đọc thêm về việc tuân thủ các bộ sưu tập tùy chỉnh trong bài đăng trên blog này của John Sundell: https://medium.com/@johnsundell/creating-custom-collections-in-swift-a344e25d0bb0