显示SwiftUI字典中的第一个/最后一个常量

3duebb1j  于 2023-04-19  发布在  Swift
关注(0)|答案(1)|浏览(87)

我想知道是否可以从car中选择第一个和最后一个Bool = true将它们放置在Text中?如果可以,我可能需要将let month重写为另一个东西,例如“march”到“March”。

struct Car: Identifiable {
    let id = UUID()
    let name: String
    let january: Bool, let february: Bool, let march: Bool // etc to december
}

let cars = [
    Car(name: "Peugeot 208", january: false, february: false, march: false, april: false, may: true, june: true, july: true, august: true, september: false, october: false, november: false, december: false),
    Car(name: "Dacia Sandero", january: false, february: false, march: true, april: true, may: false, june: false, july: false, august: false, september: false, october: false, november: false, december: false)
]

struct ContentView: View {
    var body: some View {
        ForEach(cars.sorted { $0.name < $1.name }) { car in
            Text(car.name)
            Text("From \(?) to \(?)") // if Peugeot 208: From May to August
        }
    }
}

你们有什么主意吗

lf5gs5x2

lf5gs5x21#

你的数据对月份布尔值没有序列感。这就是为什么你很难得到你想要的输出。你需要给予它一些。一个选择是通过枚举。如果你使枚举符合Comparable,你会得到自动推断的序列元素的顺序。

enum Months: Comparable {
   case Jan
   case Feb 
   case Mar
   // etc
}

这样就可以以更直观的方式记录月份(我假设这是关于所有权的,但要适当地重命名属性!)

struct Car {
   let name: String
   let owned: Set<Months>
}

这反过来将允许您计算开始和结束月份。

extension Car {
   var ownership: String {
      guard !owned.isEmpty else {return "Not owned"}
      let range = owned.sorted(by: <)
      return "\(range.first!) to \(range.last!)"
   }
   
}

使用中

let car1 = Car(name: "Ford", owned: [.Feb, .Mar, .Jan])
let car2 = Car(name: "Volvo", owned: [.Mar, .Feb])

print(car1.ownership) //"Jan to Mar"
print(car2.ownership) //"Feb to Mar"

然后,您可以在SwiftUI Text视图中使用ownership属性。

相关问题