Member-only story

Error When Use Map

Jerry PM
2 min readDec 23, 2024

--

Real case on my project

Error from my real case project

Not a Medium Member? Read this Article for Free — here

This happened when I was changing the model from a mode like this.

    let secCode: String
let logo: String
let name: String
let price: Double

So, it looks like this by adding the ‘?’.

    let secCode: String?
let logo: String?
let name: String?
let price: Double?

Of course, this change causes errors in the code that already uses the model. Some code just needs to add the ‘?’ symbol, but other code requires corrections or changes. One example is the error in the ‘map’ function, which here should be replaced with ‘compactMap’.

compactMap has two main functions:

  1. It performs data transformation like map.
  2. It automatically removes nil values from the transformation results."

Here is the code in my project and how I fixed it by replacing it with compactMap.

This is an example of the error code:


tableRow(
label: "Stop Loss",
priceItems: model.trading.stopLoss.map { $0.price ?? "" },
fairValueItems: model.trading.stopLoss.map { $0.fairValue ?? "" }
)…

--

--

No responses yet