gpt4 book ai didi

ios - 使用可选的初始化程序扩展 CollectionType

转载 作者:行者123 更新时间:2023-11-30 13:42:44 26 4
gpt4 key购买 nike

protocol Decodable {
init?(data: [String: AnyObject])
}

struct A: Decodable {

var data: [String: AnyObject]!

init?(data: [String: AnyObject]) {
self.data = data
}

}

当我想创建一个对象时这有效

let d = ["name":"Rahul"]
let a = A(data: d)

我正在尝试实现以下目标,但它在编译时出现错误。

let dArray = [["name":"Rahul"],["name":"Rahul"],["name":"Rahul"]]
let aArray = [A](data: dArray)

以下代码给出错误“nil 是初始化程序中允许的唯一返回值”。

public extension CollectionType where Generator.Element: Decodable {

init?(data: [[String: AnyObject]]) {
var elements: [Generator.Element] = []

for d in data {
let element = Generator.Element(data: d)
if let element = element {
element.append(element)
}
}

return elements

}

}

====================================答案:-

public extension Array where Element: Decodable {

init?(data: [String: AnyObject]) {
var elements: [Element] = []
for d in data {
let element = Element(data: d)
if let element = element {
element.append(element)
}
}
self = elements
}

}

这将允许您使用以下代码进行初始化

let dArray = [["name":"Rahul"],["name":"Rahul"],["name":"Rahul"]]
let aArray = [A](data: dArray)

最佳答案

您的错误是因为CollectionType是一个协议(protocol),无法初始化。您是否尝试过创建一个辅助类方法来返回集合,例如

func collectionWithData(data: [[String: AnyObject]]) -> [Generator.Element] {

关于ios - 使用可选的初始化程序扩展 CollectionType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35378704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com