Как отсортировать массив целых, двойных и отрицательных чисел в 3 различных новых массивах в Swift - PullRequest
0 голосов
/ 14 мая 2018

Я понятия не имею, как отсортировать массив в три отдельных массива положительных чисел, положительных двойных чисел и всех отрицательных.

var numbers: [Any] = [4,3.9,-23,3,7.6,-51,75.3]

-> здесь было бы, если бы отфильтровать позитивы от негативов и распечатать их

//-23 -51

-> здесь фильтр для печати оставшихся INT

//4 3

-> здесь фильтр для печати оставшихся ДУБЛОВ

//3.9 7.6 75.3

Ответы [ 2 ]

0 голосов
/ 15 мая 2018

Это будет работать:

//postive ints

let one = 1
let two = 2
let seven = 7
let ninetyThree = 93

//Negative ints

let minusOne =          -1
let minusTwo =          -2
let minusSeven =        -7
let minusNinetyThree =  -93

//Doubles

let onePointSeven = 1.7
let pi = Double.pi
let sqareRootOfTwo = sqrt(2)
let minusTwentyPointThree = -20.3

//Create an array containing a mixture of types
let mixedArray: [Any] = [
one,
sqareRootOfTwo,
minusTwo,
seven,
pi,
minusTwo,
minusSeven,
minusOne,
minusNinetyThree,
two,
ninetyThree,
minusTwentyPointThree,
onePointSeven,
]


//Filter the array to just the positive Ints
let positiveInts = (mixedArray.filter {
    guard let int = $0 as? Int else { return false }
    return int >= 0
    } as! [Int])         //Cast it to type [Int]
    .sorted { $0 < $1 }  //Sort it into numeric order
print("positiveInts = \(positiveInts)")

//Filter the array to just the negative Ints
let negativeInts = (mixedArray.filter {
    guard let int = $0 as? Int else { return false }
    return int < 0
    } as! [Int])         //Cast it to type [Int]
    .sorted { $0 < $1 }  //Sort it into numeric order
print("negativeInts = \(negativeInts)")

//Filter the array to just the Doubles
let doubles = (mixedArray.filter {
    return $0 is Double
    } as! [Double])         //Cast it to type [Double]
    .sorted { $0 < $1 }     //Sort it into numeric order
print("doubes = \(doubles)")

И вывод:

positiveInts = [1, 2, 7, 93]
negativeInts = [-93, -7, -2, -2, -1]
doubes = [-20.300000000000001, 1.4142135623730951, 1.7, 3.1415926535897931]
0 голосов
/ 14 мая 2018
let array: [Double] = [-2.5, -1, 0, 3, 5.2]

let negatives = array.filter { $0 < 0 }
let positiveDoubles = array.filter { $0 > 0 }
let positiveInts = positiveDoubles.filter { $0.truncatingRemainder(dividingBy: 1) == 0 }
...