在数组计数中调用初始化程序时没有完全匹配
No exact matches in call to initializer in a count of an array
我尝试从 txt 文件中提取一些单词,但我做不到。这是我的代码:
import SwiftUI
struct ContentView: View {
@State private var allWords : [String] = []
func startGame() {
if let startWordsURL = Bundle.main.url(forResource: "start", withExtension: "txt") {
if let startWords = try? String(contentsOf: startWordsURL) {
allWords = startWords.components(separatedBy: "\n")
return
}
}
if allWords.isEmpty {
allWords = ["silkworm"]
}
fatalError("Could not load start.txt from bundle.")
}
var body: some View {
VStack{
Text(allWords.count)
.onAppear(perform: startGame)
.font(.system(size: 30))
.frame(width: 1000, height: 75)
.background(Rectangle()
.foregroundColor(.white))
.border(Color.black, width: 1)
}
}
我在行 Text(allWords.count)
上有一个错误,它告诉我“在调用初始化程序时没有完全匹配”
如果我用 allWords\[0\]
替换 allWords.count
我有一个致命错误,告诉我“索引超出范围”
我不太明白发生了什么
我已经尝试过其他功能,但总是出现类似的错误
我只想拥有例如第二个元素
提前感谢您的帮助
作为 Swift/SwiftUI 的许多 super-vague 错误消息之一,在调用初始化程序时没有完全匹配 几乎 总是 表示错误是由于类型不匹配/错误的类型被用作给定函数的输入。在您的情况下,您正在尝试将 Int
(由 .count
方法返回)与 Text()
视图一起使用,该视图采用 String
作为参数。
一些可能的解决方案:
Text(String(allWords.count))
Text("\(allWords.count)")
(归功于@Paulw11 的评论)
Text(allWords.count.description)
(归功于@lorem ipsum 的评论)
我尝试从 txt 文件中提取一些单词,但我做不到。这是我的代码:
import SwiftUI
struct ContentView: View {
@State private var allWords : [String] = []
func startGame() {
if let startWordsURL = Bundle.main.url(forResource: "start", withExtension: "txt") {
if let startWords = try? String(contentsOf: startWordsURL) {
allWords = startWords.components(separatedBy: "\n")
return
}
}
if allWords.isEmpty {
allWords = ["silkworm"]
}
fatalError("Could not load start.txt from bundle.")
}
var body: some View {
VStack{
Text(allWords.count)
.onAppear(perform: startGame)
.font(.system(size: 30))
.frame(width: 1000, height: 75)
.background(Rectangle()
.foregroundColor(.white))
.border(Color.black, width: 1)
}
}
我在行 Text(allWords.count)
上有一个错误,它告诉我“在调用初始化程序时没有完全匹配”
如果我用 allWords\[0\]
替换 allWords.count
我有一个致命错误,告诉我“索引超出范围”
我不太明白发生了什么
我已经尝试过其他功能,但总是出现类似的错误
我只想拥有例如第二个元素
提前感谢您的帮助
作为 Swift/SwiftUI 的许多 super-vague 错误消息之一,在调用初始化程序时没有完全匹配 几乎 总是 表示错误是由于类型不匹配/错误的类型被用作给定函数的输入。在您的情况下,您正在尝试将 Int
(由 .count
方法返回)与 Text()
视图一起使用,该视图采用 String
作为参数。
一些可能的解决方案:
Text(String(allWords.count))
Text("\(allWords.count)")
(归功于@Paulw11 的评论)Text(allWords.count.description)
(归功于@lorem ipsum 的评论)