在结构中的数组中搜索数组结构

时间:2018-05-22 11:10:06

标签: swift

帮我在数组中找到一个数组。在这个实现中,我返回整个数组。

[(name: "Bell 2", arr: [arrSub(sub_txt: "Test 2, 1"),arrSub(sub_txt: "Test 2, 2")])]

我需要回复:

[(name: "Bell 2", arr: [arrSub(sub_txt: "Test 2, 2")])]

//游乐场

import UIKit

struct arrSub {
    let sub_txt: String
}

struct test {
    let name: String
    let arr: [arrSub]

    init(name: String, arr: [arrSub]) {
        self.name = name
        self.arr  = arr
    }
}

var testArr = [test]()

testArr.append(test(name: "Line 1", arr: [arrSub(sub_txt: "Line 1, 1"), arrSub(sub_txt: "Line 1, 2")]))
testArr.append(test(name: "Bell 2", arr: [arrSub(sub_txt: "Bell 2, 1"), arrSub(sub_txt: "Bell 2, 2")]))
testArr.append(test(name: "Bell 2", arr: [arrSub(sub_txt: "Test 2, 1"), arrSub(sub_txt: "Test 2, 2")]))

let new = testArr.filter({
    $0.arr.contains(where: { $0.sub_txt.contains("Test 2, 2") } )        
})

print(new)

3 个答案:

答案 0 :(得分:2)

简单的test无法帮助您实现目标,因为您尝试修改arr个实例并过滤其compactMap属性。您可以使用filter代替test返回已修改的filter个实例,以防它们符合nil条件,或compactMap如果它们没有和let new = testArr.compactMap({ test->Test? in let foundArrSub = test.arr.filter({ $0.sub_txt.contains("Test 2, 2") }) if foundArrSub.count > 0 { return Test(name: test.name, arr: foundArrSub) } return nil }) {1}}只会保留非零值。

var testArr = [Test]()

testArr.append(Test(name: "Line 1", arr: [ArrSub(sub_txt: "Line 1, 1"), ArrSub(sub_txt: "Line 1, 2")]))
testArr.append(Test(name: "Bell 2", arr: [ArrSub(sub_txt: "Bell 2, 1"), ArrSub(sub_txt: "Bell 2, 2")]))
testArr.append(Test(name: "Bell 2", arr: [ArrSub(sub_txt: "Test 2, 1"), ArrSub(sub_txt: "Test 2, 2"),ArrSub(sub_txt: "Test 2, 23")]))

测试数据:

test
  

[__ lldb_expr_1.Test(名称:"贝尔2",arr:[_ _ lldb_expr_1.ArrSub(sub_txt:"测试2,2"),__ lldb_expr_1.ArrSub(sub_txt:&# 34;测试2,23和#34;)])]

您应该遵守Swift命名约定,即类型的UpperCamelCase,因此我将Test更改为arrSub并将ArrSub更改为constexpr int* foo=0; int x = 7; constexpr int* ptr=&x; int main(){}

答案 1 :(得分:0)

谢谢,@DávidPásztor。我只是略微纠正了

value desc

此搜索只会在子结构中找到一条记录。但我需要返回所有等于搜索条件的元素。

答案 2 :(得分:0)

您也可以使用reduce

let news =  testArr.reduce([test]()) { (result, testObj) -> [test] in

            let internalArray  = testObj.arr.filter({ (arraySub) -> Bool in
                return   arraySub.sub_txt.range(of:"Test 2, 2") != nil
            }).filter({ (arraySub) -> Bool in
                return   arraySub.sub_txt.range(of:"Test 2, 2") != nil
            })
        if internalArray.count > 0 {
            return result + [test.init(name: testObj.name, arr: internalArray)]
        }else{
            return result
        }
    }

    print(news)