Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 在嵌套结构中查找结构_Swift_Struct_Filtering - Fatal编程技术网

Swift 在嵌套结构中查找结构

Swift 在嵌套结构中查找结构,swift,struct,filtering,Swift,Struct,Filtering,我一直试图在嵌套结构列表中找到一个结构。有人能帮我吗 struct Places: PlacesProtocol { private(set) var id: String private(set) var name: String private(set) var childPlaces: [PlacesProtocol]? init(json: JSON) { self.name = json[“Name”] self.id

我一直试图在嵌套结构列表中找到一个结构。有人能帮我吗

struct Places: PlacesProtocol {
    private(set) var id: String
    private(set) var name: String
    private(set) var childPlaces: [PlacesProtocol]?

    init(json: JSON) {
        self.name = json[“Name”]
        self.id = json[“Id”]
        self. childPlaces = json[“ChildPlaces”].arrayValue.map { Places(json: $0) }
    }
JSON:

我试过这个:

nestedStruct.filter { $0.id == "13" }

我能够将这个JSON解析到嵌套结构中,并尝试查找Id为的结构。我尝试过筛选,但它只筛选嵌套结构的第一层。有没有一种方法可以构建递归过滤器来查找嵌套结构中的深层结构。

您可以使用递归函数执行深度优先搜索。下面是一个粗略的例子:

extension Place {

    depthFirstSearch(where closure: (Place) -> Bool) -> Place? {
        if closure(self) { return self }
        else {
            return self.chlidPlaces.first(where: { 
                $0.depthFirstSearch(where: closure)
            })
        }
    }
}


let placeID13 = mainPlace.depthFirstSearch(where: { $0.id == "13" })

可以使用递归函数执行深度优先搜索。下面是一个粗略的例子:

extension Place {

    depthFirstSearch(where closure: (Place) -> Bool) -> Place? {
        if closure(self) { return self }
        else {
            return self.chlidPlaces.first(where: { 
                $0.depthFirstSearch(where: closure)
            })
        }
    }
}


let placeID13 = mainPlace.depthFirstSearch(where: { $0.id == "13" })

在这种情况下,我建议不要使用可选的数组属性。如果没有位置,只需使用空数组。在需要存储任何元素之前,它不会在堆上分配缓冲区,因此不会占用任何额外资源。更容易使用(例如可以直接迭代)什么是
private(set)
?如果您想要一个常量,请将成员声明为
let
。如果没有位置,只需使用空数组。在需要存储任何元素之前,它不会在堆上分配缓冲区,因此不会占用任何额外资源。更容易使用(例如可以直接迭代)什么是
private(set)
?如果您想要一个常量,请将成员声明为
,让
我已经尝试过了,并且得到了这个错误。无法将“Place”类型的值转换为闭包结果类型“Bool”@Alexander@Vijay不确定在没有具体的测试用例的情况下,您希望我们如何帮助您。我已经尝试过了,但出现了这个错误。无法将“Place”类型的值转换为闭包结果类型“Bool”@Alexander@Vijay不确定在没有具体测试用例的情况下,您希望我们如何帮助您。