Veronica G Veronica G - 1 year ago 79
Swift Question

Cannot convert value of type 'Location' to expected element type 'String'

I'm having a problem trying to pass information to an array. But I'm not sure what the problem is. This is my code. I'm trying to show images and information from these particular cities whenever the user clicks on them.

var locations : [String]! = [];

override func viewDidLoad() {

let locationDescriptions = buildDescriptions()

let parisImage = UIImage(named: "paris.jpg");
let londonImage = UIImage(named: "london.jpg");
let barcelonaImage = UIImage(named: "barcelona.jpg");
let mauiImage = UIImage(named: "maui.jpg")!;
let newYorkImage = UIImage(named: "new_york.jpg");
let sanFranciscoImage = UIImage(named: "san_francisco.jpg");

let paris = Location(name: "Paris", image: parisImage!, description: locationDescriptions["Paris"]!);
let london = Location(name: "London", image: londonImage!, description: locationDescriptions["london"]!);
let barcelona = Location(name: "Barcelona", image: barcelonaImage!, description: locationDescriptions["Barcelona"]!);
let maui = Location(name: "Maui", image: mauiImage, description: locationDescriptions["Maui"]!);
let newYork = Location(name: "New York", image: newYorkImage!, description: locationDescriptions["New York"]!);
let sanFrancisco = Location(name: "San Francisco", image: sanFranciscoImage!, description: locationDescriptions["San Francisco"]!);

// This is where the error shows
locations = [paris, london, barcelona, maui, newYork, sanFrancisco];


Answer Source

The problem is that you've defined locations as an Array of Strings, not Locations. Just swap out this line:

var locations : [String]! = [];


var locations : [Location] = [];

And this should fix the type error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download