How to skip return value in function where value is expected

Viewed 456

This is the function I am using:

let values = (0..<self.data.count).map { (i) -> ChartDataEntry in
    let x = valueDate!.timeIntervalSince(startDate)
    if let a = (self.data[i]["labelvalue"] as? NSString)?.doubleValue{
        return ChartDataEntry(x: Double(x), y: a)
    } else {
        return nil
    }
}

This is causing this error:

Nil is incompatible with return type 'ChartDataEntry'

How can I skip the loop without returning any value and continue with next check?

2 Answers
let values = (0..<self.data.count).compactMap { (i) -> ChartDataEntry? in
            let x = valueDate!.timeIntervalSince(startDate)
            if let a = (self.data[i]["labelvalue"] as? NSString)?.doubleValue{
                return ChartDataEntry(x: Double(x), y: a)
            }

            return nil
        }

Replace your code with this.

compactMap - Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

You can read more about compactMap here

Based on the correct answer of Aakash to use compactMap this is a swiftier (and more efficient) version

  • x is a constant, so create it once outside of the closure.
  • TimeInterval is a type alias of Double, Double(x) is redundant.
  • (Compact)map the data array, not its indices.
  • Avoid unnecessary bridge casts.

let x = valueDate!.timeIntervalSince(startDate)
let values = self.data.compactMap { (item) -> ChartDataEntry? in
    guard let d = item["labelvalue"] as? String, let a = Double(d) else { return nil }
    return ChartDataEntry(x: x, y: a)
}
Related