Swift 4.2 coalescing while downcasting multiple variables in a single if-let

Frakcool

I recently started learning Swift, now I'm trying to safely unwrap multiple variables that come from a JSON response which might contain or not that key.

Example of the JSON response:

{
    "products: [{
        "foo": "foo"
        "bar": "bar"
    }, {
        "foo": "foo"
    }]
}

Here I'm trying the following:

let dataTask = URLSession.shared.dataTask(with: myURL) { (data, response, error) in
    guard let safeData = data else { return }

    do {
        let json = try JSONSerialization.jsonObject(with: safeData, options: .mutableLeaves)
        if let jsonDict = json as? [String : Any] {
            let productArray = jsonDict["products"] as? [[String : Any]]
            for product in productArray! {
                if let foo = product["foo"] as? String, let bar = product["bar"] as? String {
                    let prod = Product(foo: foo, bar: bar)
                    products.append(prod)
                }
            }
        }
    } catch {
        print ("Error: \(error)")
    }
}

What I want to do is to give bar a default value (coalescing) if the value is nil, such as "Not Available" in order to display it in a label.

Is it possible? How could I do that?

Sh_Khan

You can try

 let prod = Product(foo:product["foo"] as? String ?? "Not Available" , bar: product["bar"] as? String ?? "Not Available" )

struct Root: Decodable {
    let products: [Product]
}

struct Product: Decodable {
    let foo: String
    let bar: String?

    enum CodingKeys: String, CodingKey {
        case foo , bar  
    }

    init(from decoder: Decoder) throws {

         let container = try decoder.container(keyedBy: CodingKeys.self)


        do { 
            let foo = try container.decode(String.self, forKey: .foo)  
            let bar = try container.decodeIfPresent(String.self, forKey: .bar) ?? "Not Available"
            self.init(foo:foo, bar:bar)

        } catch let error {
            print(error)
            throw error
        }
     }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Swift downcasting and protocol variables

Swift error while downcasting 'Any'

Downcasting in Swift with as and as?

DOWNCASTING IN SWIFT

Swift Pattern Matching - Switch, downcasting, and optional binding in a single statement

Multiple if let and OR condition in swift

Multiple if let in Swift

Error while assigning values to multiple variables in a single select (sql)

Swift 4 alternative if let

Multiple if let statements in Swift and Firebase

Downcasting NSObject in Swift

iOS Swift: Downcasting AnyObject

Downcasting Multidimensional Arrays Swift

Swift type casting / downcasting

Using while let with two variables simultaneously

Declaring multiple variables in single line + Angular 2 & TypeScript

swift nil coalescing with doubles

Nil Coalescing Operator Swift

Declare textfield variables to work multiple times in a if statement (swift4)

Are multiple lets in a guard statement the same as a single let?

Kotlin equivalent to swift if let? - for class variables?

How to use two let variables in an if statement in swift

Initializing variables in Swift without var/let

In Swift, when would I use a "while let"?

Is it always possible to transform multiple spatial selects with while loop and variables into a single query without using temp tables in sql?

Combining multiple across() in a single mutate() sentence, while controlling the variables names in R

Kotlin multiple variable let, using the previous variables in the next let

Javadoc multiple variables on single line

Update multiple variables in a single query