7

I am converting my code from swift 3 to swift 4 and getting this error in the following code. I am getting this even when I try to use flatmap to flatten an array

Cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')

if favoritedProducts.contains("helloWorld") {}

The below line of code does not return a [String] instead it is a '[String.Element]' How do I convert it to a [String]. If I try to cast it as a [String], it says it will always fail.

let productIDs = allItems.flatMap{$0.productID}
rghome
  • 8,529
  • 8
  • 43
  • 62
Nevin
  • 190
  • 2
  • 9

1 Answers1

5

If you have an Item type with a non optional productID property of type String like this

struct Item {
    let productID: String
}

And you have an array of Item

let allItems: [Item] = ...

Then you can get an array of productID(s) using the map method

let productIDs = allItems.map { $0.productID }

Now productIDs is [String].

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • 2
    Awesome. The issue was I was using flatmap when I just needed to use map. In swift 3 that mistake was ok but in swift 4 it didn't work because strings are now arrays of characters I believe. – Nevin Sep 23 '17 at 20:41
  • Hi, please help me. I have an array of String.Elements and when i'm goint to extract the values into a string, shows error, 'Cannot assign value of type '[String.Element]' (aka 'Array') to type 'String'. – Hilaj S L Dec 17 '17 at 09:04