Of course in actual usage we would make this an extension and check the validity of the array. I came across this post because I needed it so this one's for CGFloat, which is a Swift floating point type (Double, really)
extensionCGFloat{funcnearest(arr:[CGFloat])->CGFloat{guardarr.count>0else{fatalError("array cannot be empty")}returnarr.reduce(arr[0]){abs($0-self)<abs($1-self)?$0:$1}}}letnums:[CGFloat]=[100,200,400,800,1600,3200,6400,128000]letgiven_num=CGFloat(900)letnearest=given_num.nearest(nums)
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Swift is the most elegant concise and bestest language... ;)
Of course in actual usage we would make this an extension and check the validity of the array. I came across this post because I needed it so this one's for CGFloat, which is a Swift floating point type (Double, really)