如何在Swift中拆分数组[复制]

vaj7vani  于 2023-10-15  发布在  Swift
关注(0)|答案(1)|浏览(149)

此问题已在此处有答案

Separate odd and even indexes in a sequence array(4个答案)
13天前关闭
我有一个数组arrays1,我如何将这个数组拆分为下面的2个数组?

let arrays1 = [1, 3, 2, 4, 5, 7, 6, 8, 9, 10]

我的期望:

let listItems1 = [1, 2, 5, 6, 9]
let listItems2 = [3, 4, 7, 8, 10]

下面是我所有的代码,我想尝试将数字10listItems1移动到listItems2

let arrays1 = [1,3,2,4,5,7,6,8,9,10]
 let arrays2 = arrays1.chunked(into: 2)
        
 let listItems1 = arrays2.enumerated().filter { $0.offset % 2 == 0 }.flatMap { $0.element }

 let listItems2 = arrays2.enumerated().filter { $0.offset % 2 != 0 }.flatMap { $0.element }
extension Array {
    func chunked(into size: Int) -> [[Element]] {
        return stride(from: 0, to: count, by: size).map {
            Array(self[$0 ..< Swift.min($0 + size, count)])
        }
    }
}
eanckbw9

eanckbw91#

let arrays1 = [1, 3, 2, 4, 5, 7, 6, 8, 9, 10]
let arrays2 = arrays1.chunked(into: 2)

var listItems1 = arrays2.enumerated().filter { $0.offset % 2 == 0 }.flatMap { $0.element }
var listItems2 = arrays2.enumerated().filter { $0.offset % 2 != 0 }.flatMap { $0.element }

// Check if 10 is in listItems1, and if so, remove it from listItems1 and add it to listItems2
if let index = listItems1.firstIndex(of: 10) {
    listItems1.remove(at: index)
    listItems2.append(10)
}

print(listItems1) // [1, 2, 5, 6, 9]
print(listItems2) // [3, 4, 7, 8, 10]

相关问题