简体   繁体   English

如何在 xcode 10.2.1/swift 4.2 中使用“iterateEnum”函数按照枚举列表中指定的特定顺序对数组中的字符串值进行排序

[英]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

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:作为从 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 is a JSONEncodable modal class and Status is enum string declared within. Leave 是一个 JSONEncodable 模态类,Status 是其中声明的枚举字符串。 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.您不需要 iterateEnum 函数,只需在String之后使您的枚举符合CaseIterable协议即可访问.allCases.

Example:例子:

public enum Listing: String, CaseIterable {
    case a = "a"
    case b = "b"
}

Listing.allCases.forEach({print($0)})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM