How to split an array in half in Swift?

前端 未结 5 1754
醉梦人生
醉梦人生 2021-02-06 23:26

How do I split a deck of cards? I have an array made and a random card dealer, but have no idea how to split the deck.

Thanks everyone for the help! I now have a working

5条回答
  •  臣服心动
    2021-02-07 00:26

    And one more realization of previously provided ideas. Firstly, up to Swift current documentation, it is better to choose names in past simple tense for functions that produce some result and present tense for mutating ones. As second, as for me, it is better to choose half adding count % 2 to give more uniformed result.

    Here is it:

    extension Array {
        func splitted() -> ([Element], [Element]) {
            let half = count / 2 + count % 2
            let head = self[0..

    And results:

    let set1 = [1, 2, 3, 4, 5, 6, 7,8]
    let set2 = [1, 2, 3, 4, 5]
    let set3 = [1]
    let set4 = [Int]()
    
    print(set1.splitted())
    print(set2.splitted())
    print(set3.splitted())
    print(set4.splitted())
    
    ([1, 2, 3, 4], [5, 6, 7, 8])
    ([1, 2, 3], [4, 5])
    ([1], [])
    ([], [])
    

提交回复
热议问题