Search code examples
arraysswiftstringcharacter

No exact matches in call to subscript


I have an array of strings ["apple", "banana", "cabbage"], and I want to get the first letter of a random one and then the next letter after it on another array. That is why I'm looking for the firstIndex, to get the letter after it but on let char = Array(word)[firstIndex] I get the error:

No exact matches in call to subscript 

I'm trying to get a letter from a String, after the index of

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]
    }
}

I'm trying to convert String to Arrays to get this done but I'm not getting much luck :/


Solution

  • It's unclear how you expect your code to work, or even what you want, but I think this might solve your problem.

    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
    }
    

    Note: if the word does not have enough characters to give you a value at position it is discarded and the next one tried.