Search code examples
iosswiftnsarray

How to Create and Sort an Array of Dictionaries of Floats


I have a custom object that contains some properties that are floats (as well as others that are strings, dates etc.). Discarding the non-float properties, I would like to filter out non-zero properties, sort them by size and display them. As a swift newbie, however, I'm having trouble.

My object looks like this:

@objc public class MyTone: NSObject {
    var title: String = ""
    var date: Date = Date()
    var val1: Float = 0
    var val2: Float = 0
    var val3: Float = 0
//...
    var val10: Float = 0;
}

My code so far based on what I've found on Google is:

let propArray: [[String: AnyObject]] = [
            ["prop": "val1" as AnyObject,
             "value": 0.3 as AnyObject],
            ["prop":  "val2" as AnyObject,
             "value": 0.2 as AnyObject],
            ["prop": "val3" as AnyObject,
             "value": 0.4 as AnyObject]
        ]

   let sortedArray = propArray.sort { (first, second,third) in
            return first["value"]?.floatValue < second["value"]?.floatValue< third["value"]?.floatValue
        }

Fixit asked me to insert the anyObject code but I am getting error 'Any Object is Not Subtype of NSNumber'. In addition, I don't really understand what first, second and so forth mean... Are these terms that the compiler understands? It seems there might be a better way to do this.

Thanks in advance for any suggestions.


Solution

  • You must be using collection method sorted because you cannot use mutating member on immutable value.

    Secondly there is no third param of sort function cloure only (first, second). See doc here

    Thirdly for first["value"]?.floatValue you must provide default value e.g '0' because it's optional.

    let sortedArray = propArray.sorted { (first, second) -> Bool in
        return first["value"]?.floatValue ?? 0 < second["value"]?.floatValue ?? 0
    }