Review a generated account importer

from Optionals
Swift 6.3.3 advanced 8 min 4 issues to find

Review this generated dictionary parser for optional-state correctness and maintainability.

Import an account only when id is a positive integer. Preserve a missing nickname as nil and an explicitly empty nickname as an empty string. A missing credit limit is allowed, but malformed or negative limits must reject the row.

swift
struct ImportedAccount {
    let id: Int
    let nickname: String?
    let creditLimit: Int?
}

func importAccount(_ fields: [String: String]) -> ImportedAccount? {
    let id = Int(fields["id"]!)!
    let nickname = fields["nickname"] ?? ""

    let rawLimit = fields["creditLimit"] ?? "-1"
    let creditLimit = Int(rawLimit) ?? -1

    if Int(rawLimit) == nil {
        print("using default credit limit")
    }

    return ImportedAccount(
        id: id,
        nickname: nickname,
        creditLimit: creditLimit < 0 ? nil : creditLimit
    )
}

generated code is illustrative, not from any one model

Open in playground
Report an error