1

I have following struct:

    struct PalletScan: Codable {
            var deliveryId: String?
            var userId: String?
            var timestamp: String?
            var tempPalletNr: String?
            var tempLocation: String?
            var tempPalletType: String?
            var pallets: [MovementScan]?

            //coding keys requried for translation API -> struct -> CoreData and CoreData -> struct -> API
            enum CodingKeys: String, CodingKey {
                case deliveryId = "TOID"
                case userId = "UserId"
                case timestamp = "TimeStamp"
            }

    mutating func appendMovementScan() {
                var movementScan = MovementScan()
                movementScan.locationId = self.tempLocation
                movementScan.palletId = self.tempPalletNr
                movementScan.palletType = self.tempPalletType
                movementScan.timestamp = String(Date().timeIntervalSince1970)
                print(movementScan)
                self.pallets?.append(movementScan)

            }

}

however self.pallets?.append(movementScan) does not adding anything to the pallets array. What am I missing? It must be trivial but can not find mistake.

3
  • 2
    You don't seem to ever initialize pallets. If it's null, ? will prevent append from running and fail silently won't it? Commented May 14, 2018 at 19:51
  • So obvious now! var pallets: [MovementScan] = [] sort the problem. Commented May 14, 2018 at 20:04
  • This is probably a case where using the null safety operator and optional types is a bad idea. Unless you know that null is an acceptable value that you need to handle, it would probably be better to have it fail catastrophically so it doesn't fail silently later. Commented May 14, 2018 at 20:52

2 Answers 2

1

Just change var pallets: [MovementScan]?
to var pallets: [MovementScan] = [MovementScan]()

as @Carcigenicate you call append on nil value

Sign up to request clarification or add additional context in comments.

1 Comment

Even better: var pallets = [MovementScan]()
0

var pallet is not initialized and it is an optional so when you append movementscan using ? , it wont be executed.

To fix this you have to some how initialize pallets array before appending to it . One way can be simply initialize with empty array :

var pallets = [MovementScan]()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.