簡體   English   中英

當我遍歷列表中的數組時,出現“編譯器無法進行類型檢查”錯誤?

[英]When I loop through an array in a list, I get "compiler is unable to type-check" error?

我正在制作這個應用程序,並且我有一個日志頁面,您可以在其中查看您之前登錄的時間。 我遍歷了我的日志數組,但是當我嘗試在循環中顯示數組中的值時,我得到“編譯器無法在合理的時間內對該表達式進行類型檢查;嘗試將表達式分解為不同的子表達式”錯誤。 這是 logView swift 文件的代碼,還有更多文件,如果您需要,我可以給您,謝謝。

import SwiftUI

struct LogView: View {
 
 @AppStorage("log") private var log: [String] = []
 
 var body: some View {
     List{
         ForEach(0...log.count, id: \.self) { index in
             if(index % 2 == 0 && index != 0){
                 NavigationLink{
                    Text("log detail view")
                 }label: {
                     HStack{
                         Text(index)
                         Spacer()
                         Text(index+1)
                     }
                 }
             }
         }
     }
     .navigationTitle("Log")
     .listStyle(GroupedListStyle())
 }
}

struct LogView_Previews: PreviewProvider {
 static var previews: some View {
     RatingView(rating: .constant(3))
 }
}

非常感謝任何和所有提示,謝謝!

從您最后的評論中,我了解到您需要以下內容。 有一個結構LogItem ,它使用 id、創建日期/時間的時間戳和一條消息進行初始化。 它還包含 2 個函數,分別以格式化字符串的形式提供日期和時間。 Id、date 和 message 現在是 var 以匹配 Codable 協議。

LogView中,有一個嵌套在 NavigationView 中的列表,因此您可以使用 NavigationLinks 到詳細信息頁面(為此有一個新視圖LogDetailedView

To add items to the array it is similar to the string array you used before, array has the function append, but instead of appending a string, you have to append an object of type LogItem. 為了展示它是如何工作的,我還添加了一個按鈕,該按鈕創建一個帶有消息"Log Message"的新 LogItem 實例,這只是一個示例,您必須根據需要對其進行調整。

//
//  Log.swift
//  Log
//
//  Created by Sebastian on 23.08.22.
//

import SwiftUI

struct LogItem: Identifiable, Hashable, Codable {
    var id = UUID().uuidString
    var date = Date()
    var message: String
    
    func getDate() -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd/MM/yyyy"
        return dateFormatter.string(from: date)
    }
    
    func getTime() -> String {
        let calendar = Calendar.current
        let hour = calendar.component(.hour, from: date)
        let minutes = calendar.component(.minute, from: date)
        let seconds = calendar.component(.second, from: date)
        return ("\(hour):\(minutes):\(seconds)")
    }
}

struct ContentView: View {
    var body: some View {
        LogView()
    }
}

struct LogView: View {
    
    // Example text for new log events
    let exampleLogMessage = "Log Message"
    
    @AppStorage("logs") var logs: [LogItem] = []
    
    func addLogItem(message: String) {
        logs.append(LogItem(message: message))
    }
    
    var body: some View {
        NavigationView() {
            VStack(){
                List() {
                    ForEach(self.logs, id: \.self){ item in
                        NavigationLink(destination: LogDetailedView(logItem: item)) {
                            HStack() {
                                Text("\(item.getDate())")
                                Spacer()
                                Text("\(item.getTime())")
                            }
                        }
                    }
                }
                // This button is just an example how to add items to the array, please see also the function that gets called addLogItem(message: String)
                Button(action: {
                    self.addLogItem(message: exampleLogMessage)
                }) {
                    Text("Log Event")
                }
            }
        }
    }
}

struct LogDetailedView: View {
    
    var logItem: LogItem
    
    var body: some View {
        VStack() {
            Text("Date: \(logItem.getDate())")
            Text("Time: \(logItem.getTime())")
            Text("Message: \(logItem.message)")
        }
    }
}

要將@AppStorage與自定義 object數組一起使用,必須符合 RawRepresentable,您可以使用以下代碼/擴展來實現這一點(只需在項目的某處添加一次):

extension Array: RawRepresentable where Element: Codable {
    public init?(rawValue: String) {
        guard let data = rawValue.data(using: .utf8),
              let result = try? JSONDecoder().decode([Element].self, from: data)
        else {
            return nil
        }
        self = result
    }

    public var rawValue: String {
        guard let data = try? JSONEncoder().encode(self),
              let result = String(data: data, encoding: .utf8)
        else {
            return "[]"
        }
        return result
    }
}

這里有 2 個屏幕截圖(1. LogView - 帶有可用日志列表;2. LogDetailedView - 帶有日志詳細信息(日期、時間和消息):

1. LogView - 帶有可用日志列表

2. LogDetailedView - 帶有日志詳細信息(日期、時間和消息)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM