【问题标题】:Error Ambiguous reference to member 'indices' in SwiftUISwiftUI 中对成员“索引”的错误引用不明确
【发布时间】:2020-02-28 04:23:59
【问题描述】:

我正在尝试遍历从我的 API 收到的所有日期,并将它们转换为我的应用程序可用的格式。我在这段代码中遇到了错误

 ForEach(dateList.indices, id: \.self) { date in
    self.que = "";
    for letter in dateList[date] {
       if letter == "T" {
          dateList[date] = self.que
          return
       }
       else if letter == "-" {
          self.que = self.que + "/"
       }
       else {
         self.que = self.que + letter;
      }
   }
}

我正在尝试对 dateList 数组中的每个字符串进行迭代,并将其转换为可在我的应用程序中使用的格式。此格式将从 2020-02-28T03:32:44Z 变为 2020/02/28。我收到错误“对成员'索引'的模糊引用”,我不确定这意味着什么。

【问题讨论】:

标签: ios arrays xcode foreach swiftui


【解决方案1】:

struct ForEach 仅用于显示视图:

/// A structure that computes views on demand from an underlying collection of
/// of identified data.
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public struct ForEach<Data, ID, Content> where Data : RandomAccessCollection, ID : Hashable { ... }

例如你可以用它来显示一些List的行

List {
    ForEach(dateList.indices, id: \.self) { dateIndex in Text("\(self.dateList[dateIndex])") }
}

这与计算que 之类的变量无关,您应该将此计算提取到某个函数中并从onAppear 中调用它。这是ForEachforEach区别的一个小例子:

struct SomeLoopData: View {

    @State var dates = ["2020/02/28", "2020/02/29"]
    var body: some View {
        List {
            ForEach(dates.indices) { index in Text("\(self.dates[index])") }
                .onAppear {
                    self.compute()
            }
        }

    }

    func compute() {

        dates.indices.forEach { index in
            print(dates[index])
        }

    }
}

【讨论】:

    猜你喜欢
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多