枚举以映射到可比较的关键路径



我正在编写一些代码,其中用户可以选择如何对特定的数据数组进行排序。我试着看看是否可以在枚举中保存允许的排序属性集。我想要表达的是:

import Foundation
struct MyStruct {
let a: Int
let b: Int
}
enum MyStructProps {
case a, b

func comparableKeyPath<T: Comparable>() -> KeyPath<MyStruct, T> {
switch self {
case .a: return MyStruct.a
case .b: return MyStruct.b
}
}
}

目前每种情况都返回一个编译错误:key path value type 'Int' cannot be converted to contextual type 'T'.

查看后Swift泛型,约束和keypath,我需要将其嵌入到sort函数中,以便Swift知道如何派生泛型键路径的类型。

但是我很好奇地想知道是否有一种方法可以在我的幼稚代码中返回通用键盘?

如果您需要在比下面更中级的级别上工作,您需要键入-erase,正如Sweeper在评论中所说的。

否则,因为不能从一个函数返回不同的类型,所以只需在中间步骤中使用泛型,并在使用多个类型的过程结束时使用一个函数。

extension Sequence where Element == MyStruct {
func sorted(by property: Element.ComparableProperty) -> [Element] {
switch property {
case .a: return sorted(by: .a)
case .b: return sorted(by: .b)
}
}
}
extension MyStruct {
enum ComparableProperty {
case a, b
}
}
public extension Sequence {
/// Sorted by a common `Comparable` value.
func sorted<Comparable: Swift.Comparable>(
by comparable: (Element) throws -> Comparable
) rethrows -> [Element] {
try sorted(by: comparable, <)
}
/// Sorted by a common `Comparable` value, and sorting closure.
func sorted<Comparable: Swift.Comparable>(
by comparable: (Element) throws -> Comparable,
_ areInIncreasingOrder: (Comparable, Comparable) throws -> Bool
) rethrows -> [Element] {
try sorted {
try areInIncreasingOrder(comparable($0), comparable($1))
}
}
}

最新更新