Paul
Paul

Reputation: 4430

Swift ui codable struct with empty fields

I have the following structs:

struct ResponseToken: Identifiable, Codable, Hashable {
    var id: UUID { return UUID() }
    let access_token: String
    enum CodingKeys: String, CodingKey {
        case access_token
    }
}

struct ResponseUserInfo: Identifiable, Codable, Hashable {
    var id: UUID { return UUID() }
    let login, avatar_url, html_url, created_at, updated_at: String
    let public_repos, public_gists, followers, following: Int
    enum CodingKeys: String, CodingKey {
        case login, avatar_url, html_url, public_repos, public_gists, followers, following, created_at, updated_at
    }
}

I would like to avoid doing this every time to declare empty objs:

var token: ResponseToken = ResponseToken(access_token: "")

var userInfo: ResponseUserInfo =
ResponseUserInfo(login: "", avatar_url: "", html_url: "", created_at: "", updated_at: "", public_repos: 0, public_gists: 0, followers: 0, following: 0)

The result I would like to have is something like this:

var token: ResponseToken = ResponseToken()
var userInfo: ResponseUserInfo = ResponseUserInfo()

Can you give me a hand?

Upvotes: 0

Views: 414

Answers (1)

vadian
vadian

Reputation: 285069

A possible solution is a static property which creates an empty struct for example

struct ResponseToken: Identifiable, Codable, Hashable {
    let id = UUID()
    let accessToken: String
    enum CodingKeys: String, CodingKey {
        case accessToken = "access_token"
    }

    static let empty = ResponseToken(accessToken: "")
}

and use it

let token = ResponseToken.empty

Notes:

  • The computed property to return an UUID is pointless, declare a constant.
  • If you are specifying CodingKeys anyway, use them also to convert the snake_case keys.

Upvotes: 2

Related Questions