作为从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 activitiesLeave是一个JSONEncodable模式类,状态是在其中声明的枚举字符串。任何帮助都将不胜感激。提前谢谢。
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
}
}发布于 2019-11-23 17:31:13
尝试以下操作:
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
}发布于 2019-11-23 17:38:29
你不需要iterateEnum函数,只需在String之后使你的enum符合CaseIterable协议,就可以访问.allCases.
示例:
public enum Listing: String, CaseIterable {
case a = "a"
case b = "b"
}
Listing.allCases.forEach({print($0)})https://stackoverflow.com/questions/59004329
复制相似问题