randombits
randombits

Reputation: 48450

Swift 3: append characters to an Array

I have a Swift 3 array that's initialized with the following:

var foo: [String] = []

In one of my methods that gets invoked recursively, I'm attempting to convert a string into an array of characters, but append those characters versus doing a direct assignment to foo. So this will compile:

self.foo = text.characters.map { String($0) }

But the following breaks:

self.foo.append(text.characters.map { String($0) })

The error it produces is: 'map' produces '[T]', not expected contextual result type 'String'

What's the correct way to approach this?

Upvotes: 0

Views: 1311

Answers (1)

ZeMoon
ZeMoon

Reputation: 20274

You need to be using the append(contentsOf:) method instead.

foo.append(contentsOf: text.characters.map { String($0) })

This method can take an array of the defined type.

Whereas the append() method expects a single element to add at the end of the array.

Upvotes: 6

Related Questions