2

Scenario: I have a struct within a Struct that is used to hold JSON data.
Goal: I want to be be able to populate the sub struct via an init() for some UnitTesting work.

struct PortEligibility: Codable {
    var myVar = ""
    struct PortMobileNumber: Codable {
        let one: String?
        let two: String?
        let three: String?
    }
}

I've been toying about this but am lost: enter image description here

I don't want to use a decoder.
Remedy?

Frederick C. Lee
  • 9,019
  • 17
  • 64
  • 105

2 Answers2

1

You get the memberwise initializer if the struct base definition doesn't have any custom init methods.

let number = PortEligibility.PortMobileNumber(one: "one", two: "two", three: "three")

Also, You can either provide default value of nil or ""(empty string) or specify the default value is nil with the struct's definition and make the empty initializer available for the struct, like this:

// Sample 1
let number = PortEligibility.PortMobileNumber(one: nil, two: nil, three: nil)
// or Sample 2
struct PortEligibility: Codable {
    var myVar = ""
    struct PortMobileNumber: Codable {
        var one: String? = nil
        var two: String? = nil
        var three: String? = nil
    }
}
let number = PortEligibility.PortMobileNumber()
Frankenstein
  • 15,732
  • 4
  • 22
  • 47
0

I believe I have the solution:

let number = PortEligibility.PortMobileNumber(one: "One", two: "Two", three: "Three")

struct PortEligibility: Codable {
    var myVar = ""
    struct PortMobileNumber: Codable {
        var one: String? = nil
        var two: String? = nil
        var three: String? = nil
        init(one: String?, two: String?, three: String?) {
            self.one = one
            self.two = two
            self.three = three
        }
    }

    public func getNumber() -> PortMobileNumber {
        let portMobileNuber = PortMobileNumber(one: "Hello",
                                               two: "Every",
                                               three: "Body")
        return portMobileNuber
    }
}

var portEligibility = PortEligibility()
portEligibility.myVar = "Hello World!"

print(portEligibility)
print(portEligibility.getNumber())

print(number)

Output:

PortEligibility(myVar: "Hello World!") PortMobileNumber(one: Optional("Hello"), two: Optional("Every"), three: Optional("Body")) PortMobileNumber(one: Optional("One"), two: Optional("Two"), three: Optional("Three"))

Frederick C. Lee
  • 9,019
  • 17
  • 64
  • 105