How do I return safely unwrapped optionals which are outside of their scope?

user12741227

I'm a noob, bear with me:

func createEmployeeCode() -> String? {
    let email = UserDefaults.standard.object(forKey: "email_Saved") as? String
    let employeeCode = UserDefaults.standard.object(forKey: "employeeCode_Saved") as? String

if let emailString = email,
    let employeeCodeString = employeeCode {
    return (emailString+employeeCodeString)
}

return (emailString+employeeCodeString) //ERROR: Use of unresolved identifier 'employeeCodeString' & Use of unresolved identifier 'emailString'
}

I understand the reason the error shows is because I'm trying to return something that is in a different scope here, but how else can I get the function to return the 2 strings together without the "Optional[...]" tag?

andyvn22

(Sidenote: use UserDefaults.standard.string(forKey:).)

The issue is that you can't know if those strings DO both exist or not--if they do, you already have a great if let that returns your answer. The question now is what do you want to do if one or both are nil? Maybe you'd like to return nil from the entire function. If so,

func createEmployeeCode() -> String? {
    let email = UserDefaults.standard.string(forKey: "email_Saved")
    let employeeCode = UserDefaults.standard.string(forKey: "employeeCode_Saved")

    if let emailString = email,
        let employeeCodeString = employeeCode {
        return (emailString+employeeCodeString) //successful unwrapping, let's concatenate!
    }

    return nil //if one or both `if let`s fail, we end up here
}

Of course, you could do whatever you'd like in that "bad" case. Maybe you'd like to show whatever string you DO have. In that case:

func createEmployeeCode() -> String {
    let email = UserDefaults.standard.string(forKey: "email_Saved")
    let employeeCode = UserDefaults.standard.string(forKey: "employeeCode_Saved")

    return (email ?? "") + (employeeCode ?? "") //this works in the "good" case, too, and uses the nil coalescing operator `??`
}

In this case, you can see that the return value is no longer optional. This is because even if neither string exists, it'll concatenate two empty strings. If this feels icky, you could keep your optional return value and do a quick check before returning:

if email == nil && employeeCode == nil { return nil }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I safely unpack optionals (AlamoFire response object) in Swift

How to use Implicitly Unwrapped Optionals?

What's a concise way to safely deal with implicitly unwrapped optionals in Swift?

Are implicitly unwrapped optionals truly optionals?

How do I capture variables outside the scope of a closure in Rust?

How do I access a variable that is outside the scope in a class

How do I share dynamically loaded class outside scope

How do I access a variable outside the scope it is declared?

Implicitly Unwrapped Optionals and println

How do I safely unwrap this URL optional which i call from my database in Firebase?

How do I return jsx from an outside function with callback?

In MongoDB, how do I safely remove documents which contain an empty array?

Rust - How can I return multiple variables from a function such that they are accessible outside the scope the function is called in?

How do I return an object from another model in a scope?

Protocol conformance with implicitly unwrapped optionals

Implicitly Unwrapped Optionals in Initialization - Swift

In Swift, how do I avoid both optionals and nil object references?

How Do I Safely Scan for Integer Input?

How do I share class members, safely?

How do I safely JSON.stringify?

How do I safely uninstall gnupg?

How do I safely run memcached?

Postgres: How do I safely remove a replica?

How do I safely remove gwibber?

How do I get an ng-show to work inside an ng-repeat on a variable declared outside that scope?

How do I access a variable, created outside of an IF/ELSE scope, update it in the IF statement, and access that update in the ELSE statement?

How do I add code outside the scope of Main when using c# 9 Top Level Statements?

How do I use variable created in a scope outside of it or at least a way around this

How do I return a value which was changed in a for loop?