[英]How to use 'iterateEnum' function in xcode 10.2.1/swift 4.2 to sort string value from array in specific order as specified in the enum list
作為從 swift 3.0 xcode 9.4.1 到 swift 4.2 xcode 10.2.1 的代碼遷移的一部分,我面臨着 swift 3.0 中使用的數組排序方法的問題,該方法在 swift 3.x 中工作正常,但在 xcode 10.2.1/swift 上4.2 它不起作用,返回 nil 值而不是排序的數組列表:
// Statuses currently come through in an array, which is not sorted in the correct order
// The order is specific, as specified in the enum list
// Create a pre-made list of section headers, only for statuses that have valid activities
Leave 是一個 JSONEncodable 模態類,Status 是其中聲明的枚舉字符串。 任何幫助將不勝感激。 提前致謝。
open class Leave: JSONEncodable {
public enum Status: String {
case Drafts = "Drafts"
case PushedBack = "Pushed Back"
case PendingApproval = "Pending Approval"
case UpcomingLeave = "Upcoming Leave"
case History = "History"
case Booked = "Booked"
case Approved = "Approved"
case Denied = "Denied"
case ApprovedAndDeniedRequest = "Approved and Denied Request"
case Error = "Error"
}
}
var orderedSections: [Leave.Status] {
var list: [Leave.Status] = []
for status in iterateEnum(Leave.Status.self) {
list.append(status)
}
return list
}
fileprivate func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
var i = 0
return AnyIterator {
let next = withUnsafePointer(to: &i) { $0.withMemoryRebound(to: T.self, capacity: 1) { $0.pointee } }
let res: T? = next.hashValue == i ? next : nil
i += 1
return res
}
}
嘗試以下:
var orderedSections: [Leave.Status] {
var list: [Leave.Status] = []
Leave.Status.allCases.forEach { (status) in
list.append(status)
}
// for status in iterateEnum(Leave.Status.self) {
// list.append(status)
// }
return list
}
您不需要 iterateEnum 函數,只需在String
之后使您的枚舉符合CaseIterable
協議即可訪問.allCases.
例子:
public enum Listing: String, CaseIterable {
case a = "a"
case b = "b"
}
Listing.allCases.forEach({print($0)})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.