[英]How do I sort an array of int, doubles and negative numbers in 3 different new arrays in swift
I have no idea in how to sort the array into three separate arrays of positive ints, positive doubles, and all negatives.我不知道如何将数组排序为三个单独的正整数数组、正整数数组和所有负数数组。
var numbers: [Any] = [4,3.9,-23,3,7.6,-51,75.3]
--> here would have an if to filter the positives from negatives, and printing them --> 这里有一个 if 来从负片中过滤正片,并打印它们
//-23 -51
-->here a filter to print the remaining INTs -->这里有一个过滤器来打印剩余的 INT
//4 3
--> here a filter to print the remaining DOUBLES --> 这里有一个过滤器来打印剩余的 DOUBLES
//3.9 7.6 75.3
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 }
This would work:这会起作用:
//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)")
And the output is:输出是:
positiveInts = [1, 2, 7, 93]
negativeInts = [-93, -7, -2, -2, -1]
doubes = [-20.300000000000001, 1.4142135623730951, 1.7, 3.1415926535897931]
在从 Double 获得正 Int 时,将 positiveDouble 向上或向下舍入是否也有用?
positiveInts = positiveDoubles.compactMap{ Int(round(Double($0))) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.