我在尝试将信息传递给数组时遇到问题。但我不确定问题是什么。这是我的代码。我试图在用户点击它们时显示来自这些特定城市的图像和信息。
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];
}
答案 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]