我正在为 macOS 编写一个 Swift 应用程序。 我是 Swift 的初学者,所以我的问题对你来说可能看起来很愚蠢,对此我深表歉意......
我有一个包含以下两个字符串变量的类型:
struct ShortcutInfo: Identifiable {
let id: String
let name: String
}
我最常用的变量是“name”,包含文本列表。
我尝试使用 TextField 过滤列表。过滤后的列表应出现在选择器中。
@State var filteredShortcuts = ShortcutInfo(id: "", name: "").name.filter($0.lowercased().contains(searchText.lowercased()))
// body
TextField("", text: $searchText)
Picker("", selection: $selection) {
ForEach(filteredShortcuts) { item in
Text(item)
}
}
但我收到错误“无法在属性初始值设定项中使用实例成员“searchText”;属性初始值设定项在“self”可用之前运行”。我的代码有什么问题?
完整代码:
@State var shortcuts = [ShortcutInfo]()
@State var selection = ""
@State var searchText: String = ""
@State var filteredShortcuts = ShortcutInfo(id: "", name: "").name.filter($0.lowercased().contains(searchText.lowercased()))
// body
TextField("", text: $searchText)
Picker("", selection: $action1a) {
ForEach(filteredShortcuts) { item in
Text(item)
}
}
.task {
let shortcuts = (try? await loadShortcutNames()) ?? []
self.shortcuts = shortcuts
selection = shortcuts.first?.id ?? ""
}
//
func loadShortcutNames() async throws -> [ShortcutInfo] {
let process = Process()
process.executableURL = URL(filePath: "/usr/bin/shortcuts")
process.arguments = ["list", "--show-identifiers"]
let pipe = Pipe()
process.standardOutput = pipe
return try await withTaskCancellationHandler {
try process.run()
return try await pipe.fileHandleForReading.bytes.lines.compactMap { line in
guard let (_, name, id) = line.wholeMatch(of: /(.*) \(([A-Z0-9-]*)\)/)?.output else {
return nil
}
return ShortcutInfo(id: String(id), name: String(name))
}
.reduce(into: []) { $0.append($1) }
} onCancel: {
process.terminate()
}
}
struct ShortcutInfo: Identifiable {
let id: String
let name: String
}
extension Binding where Value == Int {
var toString: Binding<String> {
Binding<String>(
get: {
"\(wrappedValue)"
},
set: {
wrappedValue = Int($0) ?? 0
}
)
}
}
此外,我不确定我的代码在选择器中显示列表的有效性。
提前致谢。