提问人:bruno 提问时间:7/15/2023 最后编辑:bruno 更新时间:7/15/2023 访问量:73
调用下标时没有完全匹配项
No exact matches in call to subscript
问:
我有一个字符串数组 [“apple”, “banana”, “cabbage”],我想获取一个随机字符串的第一个字母,然后在另一个数组上获取它后面的下一个字母。这就是为什么我正在寻找 ,以获取它后面的字母,但我收到错误:firstIndex
let char = Array(word)[firstIndex]
No exact matches in call to subscript
我正在尝试从 索引 之后的 中获取一个字母String
func randomNumber(array: [String]) -> Int {
return Int.random(in: 0..<array.count)
}
func randomWord(array: [String]) -> String {
let randomNumberGenerated = randomNumber(array: array)
return array[randomNumberGenerated]
}
func generateRandomWord(array: [String]) -> String {
var randomNumber = randomNumber(array: array)
var word = randomWord(array: array)
var newWord = ""
if let word = word.first {
newWord = String(word)
}
if let character = newWord.last {
word = randomWord(array: array)
let firstIndex = word.firstIndex(of: character)
let char = Array(word)[firstIndex]
}
}
我正在尝试转换为完成此操作,但我没有太多运气:/String
Arrays
答:
0赞
flanker
7/15/2023
#1
目前还不清楚你期望你的代码如何工作,甚至不清楚你想要什么,但我认为这可能会解决你的问题。
func genWord( from array: [String]) -> String {
var position = 0
var solution = ""
let indicies = array.indices.shuffled() //randomises the order the words are used
for index in indicies {
let word = array[index]
if position < word.count {
let char = word[ word.index(word.startIndex, offsetBy: position, limitedBy: word.endIndex)!]
solution += String(char)
position += 1
}
}
return solution
}
注意:如果单词没有足够的字符来给你一个值,它就会被丢弃,并尝试下一个。position
评论
randomNumber(array:)