我正在关注this tutorial ,目前我正在尝试保存数组中的数据。实际上这个教程正在做我在我的表中尝试做的事情。目前我正在通过此
获取数据class Conversations {
var id: Int?
var name: String?
var is_group: Int?
var photo: String?
init(fromDictionary dict: Dictionary<String,Any>) {
if let tmp = dict["id"] as? Int {
self.id = tmp
}
if let tmp = dict["name"] as? String {
self.name = tmp
}
if let tmp = dict["is_group"] as? Int {
self.is_group = tmp
}
if let tmp = dict["photo"] as? String {
self.photo = tmp
}
}
class func getModelArray(fromArray array: [[String:Any]]) -> [Conversations] {
var conversations = [Conversations]()
for row in array {
conversations.append(Conversations(fromDictionary: row))
}
return conversations
}
在我的class GroupListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
我已声明var friendList = [Conversations]()
,该请求从请求中的json填充self.friendList = Conversations.getModelArray(fromArray: data)
我的问题是如何在教程中做到这一点,因为他对数组进行了硬编码。
我已经尝试过类似的东西但是我收到了
无法将数据'[Conversations] .Type'的值转换为dataArray中预期的参数类型'[[String:Any]]'。说实话,我也不相信它很好
class Conversations {
var id: Int?
var name: String?
var is_group: Int?
var photo: String?
init(fromDictionary dict: Dictionary<String,Any>) {
if let tmp = dict["id"] as? Int {
self.id = tmp
}
if let tmp = dict["name"] as? String {
self.name = tmp
}
if let tmp = dict["is_group"] as? Int {
self.is_group = tmp
}
if let tmp = dict["photo"] as? String {
self.photo = tmp
}
}
class func getModelArray(fromArray array: [[String:Any]]) -> [Conversations] {
var conversations = [Conversations]()
for row in array {
conversations.append(Conversations(fromDictionary: row))
}
return conversations
}
}
class ViewModelConversations {
private var conversations: Conversations
var isSelected = false
var id: Int? {
return conversations.id
}
var name: String? {
return conversations.name
}
var photo: String? {
return conversations.photo
}
var is_group: Int? {
return conversations.is_group
}
init(conversations: Conversations) {
self.conversations = conversations
}
}
let dataArray = [Conversations.getModelArray(fromArray: [Conversations])]
class ViewModel {
var conversations = [ViewModelConversations]()
init() {
conversations = dataArray.map { ViewModelConversations(conversations: $0)}
}
}
欣赏。
答案 0 :(得分:0)
class func getModelArray(fromArray array: [[String:Any]]) -> [Conversations]
这个函数需要一个字典数组作为输入,你可以在其中传递一个Conversation对象数组:
let dataArray = [Conversations.getModelArray(fromArray: [Conversations])]
所以你需要有一个字典数组才能初始化dataArray
常量