Printing optional variable
Asked Answered
A

15

122

I am trying with these lines of code

class Student {
    var name: String
    var age: Int?

    init(name: String) {
        self.name = name
    }

    func description() -> String {
        return age != nil ? "\(name) is \(age) years old." : "\(name) hides his age."
    }
}

var me = Student(name: "Daniel")
println(me.description())
me.age = 18
println(me.description())

Above code produces as follow

Daniel hides his age.
Daniel is Optional(18) years old.

My question is why there is Optional (18) there, how can I remove the optional and just printing

Daniel is 18 years old.
Arbitrament answered 15/9, 2014 at 11:1 Comment(0)
W
191

You have to understand what an Optional really is. Many Swift beginners think var age: Int? means that age is an Int which may or may not have a value. But it means that age is an Optional which may or may not hold an Int.

Inside your description() function you don't print the Int, but instead you print the Optional. If you want to print the Int you have to unwrap the Optional. You can use "optional binding" to unwrap an Optional:

if let a = age {
 // a is an Int
}

If you are sure that the Optional holds an object, you can use "forced unwrapping":

let a = age!

Or in your example, since you already have a test for nil in the description function, you can just change it to:

func description() -> String {
    return age != nil ? "\(name) is \(age!) years old." : "\(name) hides his age."
}
Washroom answered 15/9, 2014 at 12:20 Comment(2)
I think the example would be slightly better if you changed it to use if let age = age { return ""} else { return "" }Nelson
+1 for: Many Swift beginners think var age: Int? means that age is an Int which may or may not have a value. But it means that age is an Optional which may or may not hold an Int.Effluent
I
17

To remove it, there are three methods you could employ.

  1. If you are absolutely sure of the type, you can use an exclamation mark to force unwrap it, like this:

    // Here is an optional variable:

    var age: Int?

    // Here is how you would force unwrap it:

    var unwrappedAge = age!

If you do force unwrap an optional and it is equal to nil, you may encounter this crash error:

enter image description here

This is not necessarily safe, so here's a method that might prevent crashing in case you are not certain of the type and value:

Methods 2 and three safeguard against this problem.

  1. The Implicitly Unwrapped Optional

    if let unwrappedAge = age {

    // continue in here

    }

Note that the unwrapped type is now Int, rather than Int?.

  1. The guard statement

    guard let unwrappedAge = age else { // continue in here }

From here, you can go ahead and use the unwrapped variable. Make sure only to force unwrap (with an !), if you are sure of the type of the variable.

Good luck with your project!

Infernal answered 16/5, 2015 at 15:17 Comment(3)
using return age != nil ? "(name) is (age!) years old." : "(name) hides his age."Foley
Saved me a headache with an issue I had. Can't thank you enough.Swash
Swift is one hundred percent sure that the value is an optional<Int>. An optional<Int> is most definitely not an Int, so Swift is one hundred percent sure that the value is not an Int. The optional<Int> can contain an Int or no value.Catchweight
A
12

For testing/debugging purposes I often want to output optionals as strings without always having to test for nil values, so I created a custom operator.

I improved things even further after reading this answer in another question.

fileprivate protocol _Optional {
    func unwrappedString() -> String
}

extension Optional: _Optional {
    fileprivate func unwrappedString() -> String {
        switch self {
        case .some(let wrapped as _Optional): return wrapped.unwrappedString()
        case .some(let wrapped): return String(describing: wrapped)
        case .none: return String(describing: self)
        }
    }
}

postfix operator ~? { }
public postfix func ~? <X> (x: X?) -> String {
    return x.unwrappedString
}

Obviously the operator (and its attributes) can be tweaked to your liking, or you could make it a function instead. Anyway, this enables you to write simple code like this:

var d: Double? = 12.34
print(d)     // Optional(12.34)
print(d~?)   // 12.34
d = nil
print(d~?)   // nil

Integrating the other guy's protocol idea made it so this even works with nested optionals, which often occur when using optional chaining. For example:

let i: Int??? = 5
print(i)              // Optional(Optional(Optional(5)))
print("i: \(i~?)")    // i: 5
Adnopoz answered 15/6, 2016 at 18:40 Comment(3)
As of Swift 3 you can also use Swift standard library function debugPrint(_:separator:terminator:). This will however print the string in double quotes.Edrei
@Edrei : Good to know! However sometimes you might want to simply pass or embed an optional as a String somewhere else (e.g. a log/error message).Adnopoz
print(d as Any)Ogren
F
7

Update

Simply use me.age ?? "Unknown age!". It works in 3.0.2.

Old Answer

Without force unwrapping (no mach signal/crash if nil) another nice way of doing this would be:

(result["ip"] ?? "unavailable").description.

result["ip"] ?? "unavailable" should have work too, but it doesn't, not in 2.2 at least

Of course, replace "unavailable" with whatever suits you: "nil", "not found" etc

Fungal answered 22/2, 2016 at 23:6 Comment(0)
T
4

To unwrap optional use age! instead of age. Currently your are printing optional value that could be nil. Thats why it wrapped with Optional.

Tontine answered 15/9, 2014 at 11:6 Comment(0)
H
4

In swift Optional is something which can be nil in some cases. If you are 100% sure that a variable will have some value always and will not return nil the add ! with the variable to force unwrap it.

In other case if you are not much sure of value then add an if let block or guard to make sure that value exists otherwise it can result in a crash.

For if let block :

if let abc = any_variable {
 // do anything you want with 'abc' variable no need to force unwrap now.
}

For guard statement :

guard is a conditional structure to return control if condition is not met.

I prefer to use guard over if let block in many situations as it allows us to return the function if a particular value does not exist. Like when there is a function where a variable is integral to exist, we can check for it in guard statement and return of it does not exist. i-e;

guard let abc = any_variable else { return }

We if variable exists the we can use 'abc' in the function outside guard scope.

Hutchins answered 11/4, 2016 at 10:5 Comment(0)
T
3

age is optional type: Optional<Int> so if you compare it to nil it returns false every time if it has a value or if it hasn't. You need to unwrap the optional to get the value.

In your example you don't know is it contains any value so you can use this instead:

if let myAge = age {
    // there is a value and it's currently undraped and is stored in a constant
}
else {
   // no value
}
Thermy answered 15/9, 2014 at 11:12 Comment(0)
T
3

I did this to print the value of string (property) from another view controller.

ViewController.swift

var testString:NSString = "I am iOS Developer"

SecondViewController.swift

var obj:ViewController? = ViewController(nibName: "ViewController", bundle: nil)
print("The Value of String is \(obj!.testString)")

Result :

The Value of String is I am iOS Developer
Tyrannous answered 7/7, 2015 at 10:48 Comment(1)
You should not force unwrap an optionalJemmie
E
3

Check out the guard statement:

for student in class {
    guard let age = student.age else { 
        continue 
     }
    // do something with age
}
Eupatorium answered 11/4, 2016 at 9:45 Comment(0)
D
3

When having a default value:

print("\(name) is \(age ?? 0) years old")

or when the name is optional:

print("\(name ?? "unknown") is \(age) years old")

Diamagnetism answered 3/8, 2018 at 15:24 Comment(0)
P
1

I was getting the Optional("String") in my tableview cells.

The first answer is great. And helped me figure it out. Here is what I did, to help the rookies out there like me.

Since I am creating an array in my custom object, I know that it will always have items in the first position, so I can force unwrap it into another variable. Then use that variable to print, or in my case, set to the tableview cell text.

let description = workout.listOfStrings.first!
cell.textLabel?.text = description

Seems so simple now, but took me a while to figure out.

Privation answered 6/3, 2018 at 6:4 Comment(0)
P
1

This is not the exact answer to this question, but one reason for this kind of issue. In my case, I was not able to remove Optional from a String with "if let" and "guard let".

So use AnyObject instead of Any to remove optional from a string in swift.

Please refer link for the answer.

https://mcmap.net/q/182542/-cannot-get-rid-of-optional-string

Poundfoolish answered 16/7, 2018 at 7:41 Comment(0)
F
0

If you just want to get rid of strings like Optional(xxx) and instead get xxx or nil when you print some values somewhere (like logs), you can add the following extension to your code:

extension Optional {
    var orNil: String {
        if self == nil {
            return "nil"
        }
        return "\(self!)"
    }
}

Then the following code:

var x: Int?

print("x is \(x.orNil)")

x = 10

print("x is \(x.orNil)")

will give you:

x is nil
x is 10

PS. Property naming (orNil) is obviously not the best, but I can't come up with something more clear.

Felecia answered 3/3, 2021 at 11:19 Comment(0)
S
0

With the following code you can print it or print some default value. That's what XCode generally recommend I think

var someString: String?

print("Some string is \(someString ?? String("Some default"))")
Sailesh answered 4/6, 2021 at 16:23 Comment(0)
W
0

If you are printing some optional which is not directly printable but has a 'to-printable' type method, such as UUID, you can do something like this:

print("value is: \(myOptionalUUID?.uuidString ?? "nil")")

eg

    let uuid1 : UUID? = nil
    let uuid2 : UUID? = UUID.init()
    
    print("uuid1: \(uuid1?.uuidString ?? "nil")")
    print("uuid2: \(uuid2?.uuidString ?? "nil")")

-->

uuid1: nil
uuid2: 0576137D-C6E6-4804-848E-7B4011B40C11
Winze answered 15/2, 2023 at 20:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.