TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Unrap model

Forums > SwiftUI

What exactly are you trying to do? You can unwrap your model the same way you unwrap any other Optional, but I suspect that's not really what you want to know.

Ways to unwrap an Optional:

//using the unwrap operator
let name = descriptionModels?.name

//using the force unwrap operator
let name = descriptionModels!.name

//using if let
if let name = descriptionModels.name {
    //do something with name
}

//using guard let
guard let name = descriptionModels.name else {
    //exit from scope
}
//do something with name

//using the nil coalescing operator
let name = descriptionModels.name ?? "No name"

//and I'm probably forgetting more...

2      

What Are you trying to fecth? Can you give example data or the URL that you are getting data from! There may be no need to have optionals there

2      

Hi. You mean something like this?

struct Description:  Codable {
    let name, description: String
    let rating: Double
    let numberOfReviews: Int
    let price: Double
    var colors: [String]
    let imageUrls: [String]

    enum CodingKeys: String, CodingKey {
        case name, description, rating
        case numberOfReviews = "number_of_reviews"
        case price, colors
        case imageUrls = "image_urls"
    }
}

struct Descriptions: Codable {
    var descriptions = [Description]()
}

class JustForCheck: ObservableObject {
    @Published var descriptionModels = Descriptions()
}

2      

Hi @Steven_Kirke

Do you only get ONE record back?

You can do what you did before

@Published var descriptionModels: Description?

then when using (as @roosterboy said)

var body: some View {
    VStack {

        if let descriptionModels = viewModel.descriptionModels { // unwraps descriptionModels
            Text(descriptionModels.name)
        }  else {
            ProgressView() // show user something happening
        }

        Text(viewModel.descriptionModels?.name ?? "No Name") // provide default fields
    }
}

PS when decoding the JSON you can use

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

This will elimate the enum CodingKeys and make the struct Description less cluttered

2      

You're working harder than you need to.

If you tell it you're using camelCase, you don't need the CodingKeys enum, and then you don't need to write the Decodable and Encodable methods.

decoder.keyDecodingStrategy = .convertFromSnakeCase // (in whatever calls this, where you create the decoder)

See: https://www.hackingwithswift.com/articles/52/swift-4-1-improves-codable-with-keydecodingstrategy

(FWIW, when I interviewed one place, they said the most common Swift interview coding test error was trying to manually decode when the struct would auto-synthesize the coding keys and Codable methods.)

2      

Just change it slight (two lines of code)

class DecodeJson {

    func JSONDecode<T: Decodable>(data: Data, model: T, returnJSON: @escaping (T?, String?) -> Void)  {
        DispatchQueue.main.async {
            do {
                let decoder = JSONDecoder() // add decoder
                decoder.keyDecodingStrategy = .convertFromSnakeCase // convert
                let decodedUsers = try decoder.decode(T.self, from: data) // use decoder with convert from snake case
                return returnJSON(decodedUsers, "")
            } catch let error {
                print("error JSON --- \(error.localizedDescription)")
                return returnJSON(nil, "Error decode JSON \(error)")
            }
        }
    }
}

2      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.