How to condense the expansion of multiple options in Swift?

I want to expand these 6 optional variables, and if they are null, I want to give them an empty String value. This means that I can send these variables to the parameter array sent to the API.

I'm still new to Swift, and this is the only easy way to figure out how to implement this, but the internal encoder in me says it looks redundant and crap like ****.

Can someone help me to condensate this or make it easier?

    if let fbEmail = self.fbEmail {

    }else{
        self.fbEmail = ""
    }

    if let fbDob = self.fbDob {

    }else{
        self.fbDob = ""
    }

    if let fbGender = self.fbGender {

    }else{
        self.fbGender = ""
    }
    if let fbUserIp = self.fbUserIp {

    }else{
        self.fbUserIp = ""
    }
    if let fbFacebookId = self.fbFacebookId {

    }else{
        self.fbFacebookId = ""
    }
    if let fbFacebookAccessToken = self.fbFacebookAccessToken {

    }else{
        self.fbFacebookAccessToken = ""
    }
+4
source share
2 answers

You can do this exactly in 6 lines of code:

self.fbEmail  = self.fbEmail  ?? ""
self.fbDob    = self.fbDob    ?? ""
self.fbGender = self.fbGender ?? ""
self.fbUserIp = self.fbUserIp ?? ""
self.fbFacebookId = self.fbFacebookId ?? ""
self.fbFacebookAccessToken = self.fbFacebookAccessToken ?? ""

Edit: what's with the syntax ??: this is the label "if nil assigns a different value":

let c = a ?? b

c = a, a != nil, c = b.

+8

. , , . , .

, ? , , ?


:

.

// just init with a default value without them being an optional
var fbEmail : String = ""
var fbDob : String = ""

nil .isEmpty

var string : String = ""

string.isEmpty // returns true

string = "SomeString"

string.isEmpty // returns false

.

// init wit default values while still optional
var fbEmail : String? = ""
var fbDob : String? = ""

.

if let unwrfbEmail = fbEmail, let unwrfbDob = fbDob {
    // stuff available here
} else {
    // handle the error
}

guard let unwrfbEmail = fbEmail, let unwrfbDob = fbDob else {
    // put return/break here and handle the error
}
// stuff available here

. , , reset . !. , . , didSet .

// container stuct that uses didSet to avoid nil and reset to default values
struct container {

    var fbEmail : String? = "" {
        didSet {
            if fbEmail == nil {
                fbEmail = ""
            }
        }
    }
    var fbDob : String? = ""
    var fbGender : String? = ""
    var fbUserIp : String? = ""
    var fbFacebookId : String? = ""
    var fbFacebookAccessToken : String? = ""

}
+4

Source: https://habr.com/ru/post/1609875/


All Articles