MacOS swiftUI table select 单项

MacOS swiftUI table select a single item

我按照这里的示例进行操作:SwiftUI 3 MacOs Table single selection and double click open sheet

但它对我来说效果不佳。

我有这样的结构:

struct Response: Codable {
    var items: [Repository]
}

struct Repository: Codable, Identifiable {
    var number = UUID()
    var id: Int = 0
    let name: String
    let updated_at: String
    let owner: Owner
    let stargazers_count: Int
    let forks_count: Int
    let language: String?
    let description: String?

    struct Owner: Codable {
        let login: String
    }

    enum CodingKeys: String, CodingKey {
        case name, updated_at, owner, stargazers_count, forks_count, language, description
    }
}

class Api : ObservableObject{
    func loadData(query: String = "javascript", completion:@escaping ([Repository]) -> ()) {
        guard let url = URL(string: "https://api.github.com/search/repositories?q=\(query)") else {
            print("Invalid url...")
            return
        }
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data!) {
                var id = 0
                let results = decodedResponse.items.map { (repo: Repository) -> Repository in
                    var copyRepo = repo
                    copyRepo.id = id
                    id += 1
                    return copyRepo
                }
                print(results)
                DispatchQueue.main.async {
                    completion(results)
                }
            }
        }.resume()

    }
}


...

    @State var repositories = [Repository]()

    @State private var sortOrder = [KeyPathComparator(\Repository.name)]
    @State private var selectedRepository: Repository.ID?

    public var body: some View {

         if(selectedRepository != nil)//null??
         Text(repositories[selectedRepository!].name)

Table(repositories, selection: $selectedRepository, sortOrder: $sortOrder) {
                    TableColumn("Name") {
                        Text([=12=].name)
                            .frame(
                                maxWidth: .infinity,
                                maxHeight: .infinity,
                                alignment: .leading
                            )
                            .contentShape(Rectangle())
                            .contextMenu {
                                Button(action: {}) { Text("Action") }
                            }
                            /*.gesture(TapGesture(count: 2).onEnded {
                                print("pr", selectedRepository )
                            })*/
                    }

                    TableColumn("Last updated"){
                        Text([=12=].updated_at)
                    }
                    TableColumn("Owner", value: \.owner.login)
                }
                .onAppear() {
                    Api().loadData { (repositories) in
                        self.repositories = repositories
                        self.isLoading = false
                    }
                }
                .onChange(of: sortOrder) {
                    print([=12=])
                    repositories.sort(using: [=12=])
                }

    }

我想确保当用户单击 table 的一个元素时,然后激活选择以在文本字段中显示所选元素的数据,我试图让名称已打印但不起作用。

启动应用程序后出现以下错误:Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

你能帮帮我吗?

可能缺少一些字符:

if(selectedRepository != nil)//null?? <- missing '{'
    Text(repositories[selectedRepository!].name)

也写成:

if let selectedRepository = selectedRepository {
    Text(repositories[selectedRepository!].name)
    ...
}

即使没有必要我总是喜欢初始化属性(这是一种有用的东西更像是一种习惯):

@State private var selectedRepository: Repository.ID? = nil