sdd
sdd

Reputation: 877

How to skip return value in function where value is expected

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?

Upvotes: 3

Views: 1101

Answers (2)

vadian
vadian

Reputation: 285132

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)
}

Upvotes: 0

Aakash
Aakash

Reputation: 2269

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

Upvotes: 2

Related Questions