Why this struct with optional values returns nothing?

weegee

I visited this thread to know about optionals and I saw a quote from the docs, which I quote again.

If your custom type has a stored property that is logically allowed to have “no value”—perhaps because its value cannot be set during initialization, or because it is allowed to have “no value” at some later point—declare the property with an optional type. Properties of optional type are automatically initialized with a value of nil, indicating that the property is deliberately intended to have “no value yet” during initialization.

So I have the same condition. I have some variables that may have some values or not. So here's my struct

struct Notification {
    var type : String?
    var dp : String?
    var name : String?
    var postImage : String?
    var whomenc : String?
}

So I'm trying to create a struct array but whenever the struct is initialized, I get nothing in return

obj.forEach {
    guard let type = $0["type"] as? String else {return}
    print("type = \(type)")
    guard let dp = $0["dp"] as? String else {return}
    print("dp = \(dp)")
    guard let name = $0["name"] as? String else {return}
    print("name = \(name)")
    guard let postimg = $0["postimg"] as? String else {return}
    print("postimg = \(postimg)")
    guard let whomenc:String = $0["whomenc"] as? String else {return}
    print("whomenc = \(whomenc)")
    let notification = Notification(type: type, dp: dp, name: name, postImage: postimg, whomenc: whomenc)
    self.notifiArray.append(notification)
    print("notifiArray.count = \(self.notifiArray.count)") // this satement doesn't gets executed.
}

And this is what I get in the log

type = commentCommented
dp = default.jpg
name = testt
postimg = 69663rocketleague32bitdx914102018180636.mp4
type = commentCommented
dp = default.jpg
name = testt
postimg = 69663rocketleague32bitdx914102018180636.mp4
type = followed
dp = default.jpg
name = bott1
type = followed
dp = default.jpg
name = bott2

I tried printing the notification variable and it is empty. I tried printing the notifiArray which returns as []

The array is declared as

var notifiArray = [Notification]()

Any idea why this behavior?

vacawama

This statement is not succeeding:

guard let whomenc:String = $0["whomenc"] as? String else {return}

either because the key "whomenc" doesn't exist or the type isn't a String. The guard statement then returns from the closure and does nothing more for that dictionary.

Since you can create a Notification even if some values are nil, you could remove the guard statements and pass the (possibly nil) values to the Notification initializer:

obj.forEach {
    let type = $0["type"] as? String
    print("type = \(type ?? "nil")")
    let dp = $0["dp"] as? String
    print("dp = \(dp ?? "nil")")
    let name = $0["name"] as? String
    print("name = \(name ?? "nil")")
    let postimg = $0["postimg"] as? String
    print("postimg = \(postimg ?? "nil")")
    let whomenc = $0["whomenc"] as? String
    print("whomenc = \(whomenc ?? "nil")")
    let notification = Notification(type: type, dp: dp, name: name, postImage: postimg, whomenc: whomenc)
    self.notifiArray.append(notification)
    print("notifiArray.count = \(self.notifiArray.count)") // this satement doesn't gets executed.
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Why Nothing == (pure Nothing) returns False in Haskell?

Why spring data redis findById returns null values in Optional after upgrading to version 2.3.2.RELEASE

Why fs.readFileSync returns nothing inside a promise on serveside?

Why do I get a trait not implemented for an optional field in Diesel struct

Why isn't Stored Procedure returns Nothing even the parameters are correct?

Why Could Not Deduce Template Argument When Function Returns a Struct Template

Why JSONDecoder always returns nil for an optional property?

Ajax call returns nothing

Why "c:forEach" loop returns nothing in this jsp?

Ajax request returns nothing. why?

Laravel Redirect Returns Nothing

Elastic Search: Why my filtered query returns nothing?

Why XMPP function returns nothing?

Request returns nothing

if function in javascript returns nothing..why?

Why does struct.pack return these values?

MongoDB returns nothing?

python function returns nothing

function that returns table struct with values when rowIndex is given

Swift struct optional values

Why does this cycle returns different value or nothing on same index of array

Why sqlite database query returns nothing in python code?

why does the minBy() returns Optional but others dont?

BeautifulSoup returns nothing

Why does the outer query return nothing if second subquery returns no results?

Why `apt-file list msttcorefonts` returns nothing?

Create Nothing from falsey values using Returns library

tRPC mutateAsync returns nothing

why struct returns duplicate values as index in solidity?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  3. 3

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  4. 4

    pump.io port in URL

  5. 5

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    Do Idle Snowflake Connections Use Cloud Services Credits?

  9. 9

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  10. 10

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  11. 11

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  12. 12

    Generate random UUIDv4 with Elm

  13. 13

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  14. 14

    Is it possible to Redo commits removed by GitHub Desktop's Undo on a Mac?

  15. 15

    flutter: dropdown item programmatically unselect problem

  16. 16

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  17. 17

    EXCEL: Find sum of values in one column with criteria from other column

  18. 18

    Pandas - check if dataframe has negative value in any column

  19. 19

    How to use merge windows unallocated space into Ubuntu using GParted?

  20. 20

    Make a B+ Tree concurrent thread safe

  21. 21

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

HotTag

Archive