How to split an array in half in Swift?

前端 未结 5 1764
醉梦人生
醉梦人生 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:07

    You can create an extension on SequenceType, and create a function named divide.

    This function would iterate through the elements of the sequence while placing those that match the predicate into one array (slice) and those that do not match into another array (remainder).

    The function returns a tuple containing the slice and the remainder.

    extension SequenceType {
    
        /**
         Returns a tuple with 2 arrays.
         The first array (the slice) contains the elements of self that match the predicate.
         The second array (the remainder) contains the elements of self that do not match the predicate.
         */
        func divide(@noescape predicate: (Self.Generator.Element) -> Bool) -> (slice: [Self.Generator.Element], remainder: [Self.Generator.Element]) {
            var slice:     [Self.Generator.Element] = []
            var remainder: [Self.Generator.Element] = []
            forEach {
                switch predicate($0) {
                case true  : slice.append($0)
                case false : remainder.append($0)
                }
            }
            return (slice, remainder)
        }
    
    }
    

    This is an example

    let tuple = [1, 2, 3, 4, 5].divide({ $0 >= 3 })
    tuple.slice     // [3, 4, 5]
    tuple.remainder // [1, 2]
    

提交回复
热议问题