【问题标题】:SwiftUI: How to sort array indices without enumerated()SwiftUI:如何在没有枚举()的情况下对数组索引进行排序
【发布时间】:2022-11-15 12:11:49
【问题描述】:

我正在努力在 SwiftUI 中对数组进行排序。我正在使用索引在ForEach 中循环我的数组,我想对整个数组进行排序。由于CGSize 的值,我有不能为Hashable 的对象,这就是我不能使用enumerated() 的原因。经过数小时的尝试,我仍然不知道如何实现排序数组。

这是对象的代码:

struct Object: Identifiable {
  var id = UUID()
  var position: CGPoint = .zero
  var num: Int
}

和内容视图:

struct ContentView: View {
  @State var objects = [
    Object(num: 3),
    Object(num: 5),
    Object(num: 6),
    Object(num: 2),
    Object(num: 4),
    Object(num: 1)
  ]
    var body: some View {
        VStack {
          ForEach(objects.sorted(by: {$0.num > $1.num}).indices, id:\.self) { i in
            Text("\(objects[i].num)")
          }
        }
        .padding()
    }
}

【问题讨论】:

    标签: ios arrays swift swiftui


    【解决方案1】:

    您可以使用extensionCGPoint/CGSize 变为Hashable

    extension CGPoint: Hashable{
        public func hash(into hasher: inout Hasher) {
            hasher.combine(x)
            hasher.combine(y)
        }
    }
    extension CGSize: Hashable{
        public func hash(into hasher: inout Hasher) {
            hasher.combine(height)
            hasher.combine(width)
        }
    }
    

    只需在文件级别的项目中的任何位置添加上面的代码。

    然后,您可以轻松使用所有内置方法进行排序。

    struct Object: Identifiable, Hashable {
        var id = UUID()
        var position: CGPoint = .zero
        var num: Int
    }
    
     struct HashableSize: View {
        @State var objects = [
            Object(num: 3),
            Object(num: 5),
            Object(num: 6),
            Object(num: 2),
            Object(num: 4),
            Object(num: 1)
        ]
        var body: some View {
            VStack {
                ForEach(objects.sorted(by: .num), id:.id) { obj in
                    Text("(obj.num)")
                }
            }
            .padding()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      相关资源
      最近更新 更多