这不是重复的问题! 我已经搜索了许多类似的问题,但找不到像我这样的类来声明/调用数据模型。
我想将store
的信息从Table View Controller
传递到Detail View Controller
。我很难声明变量store
的正确类型以在我的Detail View Controller
中接收传递的数据。
我的商店型号:
class StoreModel{
var name: String?
var desc: String?
var url: String?
var rate: Double
init(name: String?, desc: String?, url: String?, rate: Double){
self.name = name
self.desc = desc
self.url = url
self.rate = rate
}
}
在我的Table View Controller
中,我声明了store
来保存Firebase中的数据:
class TableViewController: UITableViewController, UISearchResultsUpdating {
var storeList = [StoreModel]()
override func viewDidLoad() {
//Hide some codes that initialize Firebase connection ...
refStores.observe(DataEventType.value, with: {(snapshot) in
if snapshot.childrenCount > 0{
for stores in snapshot.children.allObjects as! [DataSnapshot]{
let storeObject = stores.value as? [String: AnyObject]
let storeName = storeObject?["storeName"]
let storeDesc = storeObject?["storeDesc"]
let storeUrl = storeObject?["storeUrl"]
let storeRate = storeObject?["storeRate"]
let store = StoreModel(name: storeName as! String?,
desc: storeDesc as! String?,url: storeUrl as! String?,
rate: storeRate as! Double)
self.storeList.append(store)
}
self.tblSearch.reloadData()
}})}
以下是我的尝试:
在我的Detail View Controller中,我声明storeList
来接收传递的数据:
var storeList = [StoreModel]()
我在Table View Controller和Detail View Controller之间创建一个序列(标识为showDetailView
)。
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
let selectedStore = storeList[indexPath.row]
let destinationVC = DetailViewController()
destinationVC.storeList = selectedStore
destinationVC.performSegue(withIdentifier: "showDetailView", sender: self)
} }
我在一行收到错误消息Cannot assign value of type 'StoreModel' to type '[StoreModel]'
destinationVC.storeList = selectedStore
,所以我认为在Detail View Controller
中声明正确类型的变量时遇到问题。
感谢帮助!
答案 0 :(得分:0)
如错误消息所述,无法将类型“ StoreModel”的值分配给类型“ [StoreModel]” 。您正在尝试将模型的单个实例分配给DetailViewController中的数组。要么声明
var storeList = StoreModel()
在DetailViewController中。或将值传递为
destinationVC.storeList = [selectedStore]
还用于创建
之类的实例var storeList = StoreModel()
提供一个无参数的初始化程序。
class StoreModel() {
var name: String?
var desc: String?
var url: String?
var rate: Double
init(name: String?, desc: String?, url: String?, rate: Double){
self.name = name
self.desc = desc
self.url = url
self.rate = rate
}
init() {
}
}
答案 1 :(得分:0)
您仅传递一个商店数据。因此,您需要在Detail View Controller中进行更改 从这个
var storeList = [StoreModel]()
到
var storeList:StoreModel!
这是因为在let selectedStore = storeList[indexPath.row]
您只选择了一个selectedStore。