swift java混合,如何在Swift中连接或合并数组?
使用Swift 3,根據您的需求和品味,您可以選擇其中一個 five following ways 來連接/合并兩個數組 .
1.使用Swift標準庫(: :)泛型運算符將兩個數組合并為一個新數組
Swift標準庫定義了一個 +(_:_:) 泛型運算符 . +(_:_:) 具有以下declaration:
func +(lhs: RRC1, rhs: RRC2) -> RRC1
通過連接兩個集合的元素來創建新集合 .
以下Playground代碼顯示如何使用 +(_:_:) generic運算符將兩個類型為 [Int] 的數組合并到一個新數組中:
let array1 = [1, 2, 3]
let array2 = [4, 5, 6]
let flattenArray = array1 + array2
print(flattenArray) // prints [1, 2, 3, 4, 5, 6]
2.使用Array的append(contentsOf :)方法將數組附加到另一個數組
Swift Array 有一個 append(contentsOf:) 方法 . append(contentsOf:) 具有以下declaration:
public mutating func append(contentsOf newElements: S) where S : Sequence, S.Iterator.Element == Element)
將序列或集合的元素添加到此集合的末尾 .
以下Playground代碼顯示如何使用 append(contentsOf:) 方法將數組附加到另一個 [Int] 類型的數組:
var array1 = [1, 2, 3]
let array2 = [4, 5, 6]
array1.append(contentsOf: array2)
print(array1) // prints [1, 2, 3, 4, 5, 6]
3.使用Sequence的flatMap(_ :)方法將兩個數組合并到一個新數組中
Swift為符合 Sequence 協議(包括 Array )的所有類型提供 flatMap(_:) 方法 . flatMap(_:) 具有以下declaration:
func flatMap(_ transform: (Self.Iterator.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Iterator.Element]
返回一個數組,其中包含使用此序列的每個元素調用給定轉換的連接結果 .
以下Playground代碼顯示如何使用 flatMap(_:) 方法將兩個 [Int] 類型的數組合并到一個新數組中:
let array1 = [1, 2, 3]
let array2 = [4, 5, 6]
let flattenArray = [array1, array2].flatMap({ (element: [Int]) -> [Int] in
return element
})
print(flattenArray) // prints [1, 2, 3, 4, 5, 6]
4.使用Sequence的joined()方法和Array的init(_ :)初始化程序將兩個數組合并為一個新數組
Swift為符合 Sequence 協議(包括 Array )的所有類型提供 joined() 方法 . joined() 具有以下declaration:
func joined() -> FlattenSequence
返回連接序列序列的元素 .
此外,Swift Array 有一個 init(_:) 初始化程序 . init(_:) 具有以下declaration:
init(_ s: S)
創建一個包含序列元素的數組 .
因此,以下Playground代碼顯示如何使用 joined() 方法和 init(_:) 初始化程序將兩個類型為 [Int] 的數組合并到一個新數組中:
let array1 = [1, 2, 3]
let array2 = [4, 5, 6]
let flattenCollection = [array1, array2].joined() // type: FlattenBidirectionalCollection]>
let flattenArray = Array(flattenCollection)
print(flattenArray) // prints [1, 2, 3, 4, 5, 6]
5.使用Array的reduce(: :)方法將兩個數組合并到一個新數組中
Swift Array 有一個 reduce(_:_:) 方法 . reduce(_:_:) 具有以下declaration:
func reduce(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
返回使用此序列的每個元素和累積值調用給定組合閉包的結果 .
以下Playground代碼顯示如何使用 reduce(_:_:) 方法將兩個類型為 [Int] 的數組合并到一個新數組中:
let array1 = [1, 2, 3]
let array2 = [4, 5, 6]
let flattenArray = [array1, array2].reduce([], { (result: [Int], element: [Int]) -> [Int] in
return result + element
})
print(flattenArray) // prints [1, 2, 3, 4, 5, 6]
總結
以上是生活随笔為你收集整理的swift java混合,如何在Swift中连接或合并数组?的全部內容,希望文章能夠幫你解決所遇到的問題。