您可以进行扩展,以便它可以返回两个数组的数组,使用Ints,Strings等:
extension Array { func split() -> [[Element]] { let ct = self.count let half = ct / 2 let leftSplit = self[0 ..< half] let rightSplit = self[half ..< ct] return [Array(leftSplit),Array(rightSplit)] } } let deck = ["J","Q","K","A"] let nums = [0,1,2,3,4] deck.split() // [["J","Q"],["K","A"]] nums.split() // [[0,1],[2,4]]
但返回一个命名元组甚至更好,因为它强制执行这样一个事实:你期望正好两个数组:
extension Array { func split() -> (left: [Element],right: [Element]) { let ct = self.count let half = ct / 2 let leftSplit = self[0 ..< half] let rightSplit = self[half ..< ct] return (left: Array(leftSplit),right: Array(rightSplit)) } } let deck = ["J","A"] let splitDeck = deck.split() print(splitDeck.left) // ["J","Q"] print(splitDeck.right) // ["K","A"]
注意:获得第一个正确答案的是Andrei和Qbyte,我只是添加信息.