gpt4 book ai didi

ios - 希望在 swift 中使用过滤器来过滤结构的内部数组而不接触外部数组

转载 作者:行者123 更新时间:2023-11-28 11:59:43 26 4
gpt4 key购买 nike

这是我创建的一个 Playground ,用于尝试创建正确的过滤器:我想要返回的是所有外部结构和任何内部数组值,这些值满足将从搜索栏入站的“文本” block 。

//: Playground - noun: a place where people can play

import UIKit
import Foundation

struct events{
var title:String
var unique:Int
var swimmers_info:[swim_info]

}

struct swim_info{
var name:String
var team:String
}

var arrayEV:[events]
var si1:[swim_info]
var si2:[swim_info]

si1 = [
swim_info(name:"Smith, John",team:"PHNX"),
swim_info(name:"Tenay, Teresa",team:"CRIM")
]

si2 = [
swim_info(name:"Test, Two",team:"PHNX"),
swim_info(name:"Female, Swimmer",team:"SSA")
]


arrayEV = [
events(title: "First Event",unique: 5,swimmers_info:si1),
events(title: "Second Event",unique: 2,swimmers_info:si2)
]

//print(arrayEV)

var newarrayEV1 = arrayEV.filter({(value) -> Bool in
return value.swimmers_info.contains(where: {$0.team == "SSA"})
})

var newarrayEV2 = arrayEV.map({$0.swimmers_info.filter({(value) -> Bool in
return value.team == "SSA"
})})


print(newarrayEV1)

YEILDS [__lldb_expr_42.events(title: "Second Event", unique: 2, swimmers_info: [__lldb_expr_42.swim_info(name: "Test, Two", team: "PHNX"), __lldb_expr_42.swim_info(name: "Female") , 游泳者", 团队: "SSA")])]

**不正确,因为它只产生第二个主结构和两个子结构

print("  ")
print(newarrayEV2 )

[[], [__lldb_expr_42.swim_info(name: "Female, Swimmer", team: "SSA")]]

不正确,因为删除了所有主要结构信息

print("11")

有点正确

我可以通过以下方式获得所需的结果:

for (index,loop) in arrayEV.enumerated(){
//print(String(describing: index))
//print(loop.swimmers_info)
var new_si = loop.swimmers_info.filter({(value) -> Bool in
return value.team == "SSA"
})
//print(new_si)
arrayEV[index].swimmers_info = new_si

}

但是我不确定这是否是解决此问题的最佳方式。

最佳答案

根据您建议的“解决方案”,我认为这就是您所追求的:

arrayEV = arrayEV.map {
var ev = $0
ev.swimmers_info = ev.swimmers_info.filter {$0.team == "SSA"}
return ev
}

之所以使用看起来相当笨拙的三行代码,是因为我们不能改变结构的属性,除非对结构本身的引用是 var 引用——但是 map为我们提供了一个 let 引用 ($0)。

关于ios - 希望在 swift 中使用过滤器来过滤结构的内部数组而不接触外部数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50331190/

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