[SOLVED] Merge Array of String – No exact matches in call to subscript

Issue

I’m getting an Xcode error

Global function ‘zip’ requires that ‘String.Element’ (aka ‘Character’) conform to ‘Sequence’

on array[i] = zip(array[i], arrayOfZeros)

func expandedForm(_ num: Int) -> String {
  
    let lenght = String(num).count
    var array = Array(String(num))
    
    var i = 0
    while array.count > i {
        
        let numberOfZeros = array.count - 1 - i
        let arrayOfZeros = Array(repeating: "0", count: numberOfZeros)
        let string = array[i]
        array[i] = zip(array[i], arrayOfZeros)
        i += 1
    }
    
    return ""
}

I’m trying to merge two array of strings, but I think they are not the same type. Need some help on this.

Solution

func expandedForm(_ num: Int) -> String {
  
    let lenght = String(num).count
    var array = Array(String(num))
    
    var i = 0
    while array.count > i {
        
        let numberOfZeros = array.count - 1 - i
        let arrayOfZeros = Array(repeating: "0", count: numberOfZeros)
        let string = array[i]
        array[i] = zip(array[i], arrayOfZeros)
        i += 1
    }
    
    return ""
}

You have some issues.

var array = Array(String(num)), if you pass your cursor on array, it’s a [String.Element], ie a [Character], an array a Character.

So let string = array[i], that’s misleading, because array[i] is a Character, not a String.

zip(_:_:) awaits for two sequences (~array), and you give as first parameter a Character.

Possible solutions:

Make array, a real array of String:

var array = Array(String(num)).map { String($0) }

And then:

array[i] = array[i] + arrayOfZeros.joined()

Or create a new variable var output that will be an array of String:

var output: [String] = []

And populate it:

output.append(String(array[i] + arrayOfZeros.joined())

Answered By – Larme

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published.