As a part of code migration from swift 3.0 xcode 9.4.1 to swift 4.2 xcode 10.2.1, I am facing a issue with array sortting method used in swift 3.0 which work fine in swift 3.x but on xcode 10.2.1/swift 4.2 its doesn't work, return nil value instead of sorted array list:
// 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 is a JSONEncodable modal class and Status is enum string declared within. Any help would be appreciate. Thanks in advance.
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
}
}
Try following :
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
}
You don't need iterateEnum function just make your enum conform to CaseIterable
protocol after String
, to access .allCases.
Example:
public enum Listing: String, CaseIterable {
case a = "a"
case b = "b"
}
Listing.allCases.forEach({print($0)})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.