无法将“位置”类型的值转换为预期的元素类型“String”

时间:2016-07-28 19:44:52

标签: arrays swift xcode

我在尝试将信息传递给数组时遇到问题。但我不确定问题是什么。这是我的代码。我试图在用户点击它们时显示来自这些特定城市的图像和信息。

var locations : [String]! = [];

    override func viewDidLoad() {
    super.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];

}

2 个答案:

答案 0 :(得分:1)

问题在于您已将locations定义为String的数组,而不是Location。只需换掉这一行:

var locations : [String]! = [];

var locations : [Location] = [];

这应该可以解决类型错误。

答案 1 :(得分:0)

问题是您要将类型Location的值添加到应包含String的数组中。

这将解决问题

locations = [paris.name, london.name, barcelona.name, maui, newYork.name, sanFrancisco.name]