Are Doubles Comparable in Swift

Vince O'Sullivan

Swift 3, Xcode 8β2.
I've implemented a class that sorts Comparable data and attempted to test it using Doubles. Unfortunately, I'm getting the error "Cannot convert value of type '[Double]' to specified type '[T]'.". I've reproduced the error in the sample code below:

class foo<T: Comparable> {
    let data: [T]  = [Double]()
}

Am I right is assuming that Doubles are Comparable and, if so, how do I eliminate the error above?
Thx.

Eric Aya

Your property has a generic type, T: it can't be declared as holding a concrete type. Just use [T] in the declaration, and use Double when instantiating the class.

For my example I've also made the property a var so that I could modify it:

class Foo<T: Comparable> {
    var data: [T] = [T]()
}

let f = Foo<Double>()
f.data = [42.0, 33.0]
f.data.sort()
print(f.data)

Gives

[33.0, 42.0]

as expected.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Mergesort to sort doubles in java. Problems with comparable

Swift comparable on a protocol

Understanding the Doubles and Ints in Swift

swift nil coalescing with doubles

NSIntegers for Doubles in Swift

Algorithm for LCM of doubles in Swift

Multiplying variables and doubles in swift

Is there a placeholder for doubles in Swift?

Swift Ints and some Doubles working but not all Doubles

Using manual input to store either integers, doubles, or strings in a Comparable ArrayList

Generic class that conforms to Comparable in Swift

Extend @objc protocol with Comparable in Swift

Initializing an array of Doubles in Swift 4

How to cache array of Doubles in Swift

How to write a global function that uses Comparable in Swift

Redundant conformance of 'NSDate' to protocol 'Comparable' Swift

Swift generic class with numeric and comparable protocols

Swift: Implementing Comparable with computed struct property

GPUImage doubles image size - iOS/Swift

Swift - Convert values in array to doubles or floats

adding doubles contained within a dictionary swift 3

Swift 4 decoding doubles from JSON

Is it possible for a Swift enum with Comparable raw values to synthesize the Comparable protocol implementations automatically?

Is Equatable redundant in Swift (4.1 and above) since we already have Comparable?

Swift: binary operator '<' cannot be applied to two 'Comparable' operands

Apply a comparable value type Int to an UIImage object in Swift 4

Swift 4 Conform Comparable protocol and sort method issue

How to make hours and minutes of Swift's DateComponents comparable if not this way?

Comparing two Doubles in Swift: "Type of expression is ambiguous without more context"