Printing Optional Variable

Swift how to print optional string

you can do it like

print("Item: \(item)")

The way to write it in swift is like this.

And as you are sure about the existing value inside, so it can be

print("Item: \(item!)")

if in some other case, where you are not sure if the value exists or not then you can use if let

if let item = item {
print("Item: \(item)")
}

Hope it helps

Printing value of a optional variable includes the word Optional in Swift

Optional chaining is used here:

let age = self.clientDetail?.getAge()

So return of getAge() is optional value. Try optional binding:

if let age = age {
println("age.....\(age)")
}

or simply unwrap the age with age!, but this will crash your app if age is nil.

Why is the word Optional being added when I print a string using a dictionary entry as the variable?

Retrieving a value for a given key from a dictionary is always an optional because the key might not exist then the value is nil. Using String Interpolation "\(...)" the Optional is included as literal string.

To avoid the literal Optional(...) in String Interpolation you have to unwrap the optionals preferred in a safe way

if let first = person["first"] as? String, age = person["age"] as? Int {
print("Your first name is \(first) and you are \(age) years old.")
}

Why does SWIFT print Optional(...)

Swift has optional types for operations that may fail. An array index like airports["XYZ"] is an example of this. It will fail if the index is not found. This is in lieu of a nil type or exception.

The simplest way to unwrap an optional type is to use an exclamation point, like so: airports["XYZ"]!. This will cause a panic if the value is nil.

Here's some further reading.

You can chain methods on option types in Swift, which will early exit to a nil without calling a method if the lefthand value is nil. It works when you insert a question mark between the value and method like this: airports["XYZ"]?.Method(). Because the value is nil, Method() is never called. This allows you to delay the decision about whether to deal with an optional type, and can clean up your code a bit.

To safely use an optional type without panicking, just provide an alternate path using an if statement.

if let x:String? = airports["XYZ"] {
println(x!)
} else {
println("airport not found")
}

Are there any conventions for printing optional values?

I like the option of print None and Some x. I think that this immediately describes what's going on (especially for people familiar with Haskell).

Personally, I would not use the [] and [x] alternative, because many languages use the square brackets to denote some sort of list. If I were to see that output, I would immediately be thinking that a list had been printed, as opposed to an optional type.

How to print a string from plist without Optional?

One way to get rid of the Optional is to use an exclamation point:

println(todayTitle!)

However, you should do it only if you are certain that the value is there. Another way is to unwrap and use a conditional, like this:

if let theTitle = todayTitle {
println(theTitle)
}

Paste this program into runswiftlang for a demo:

let todayTitle : String? = "today"
println(todayTitle)
println(todayTitle!)
if let theTitle = todayTitle {
println(theTitle)
}

Why are implicitly unwrapped variables now printing out as some(...) in Swift 4.1?

String! is an implicitly unwrapped optional but it's still an optional.

The value will get unwrapped to a non-optional only in situations when it has to be unwrapped, e.g. when being passed to a function that cannot take an optional. However, print can accept an optional and String! will be treated just as String?.

This change actually happened in Swift 3 already as part of SE-0054.

In your example:

var aString: Int!
let aBool = true
if aBool {
aString = 2
}

print(aString)

You should not be using an implicitly unwrapped optional because since it's a var, it get initialized to nil. You should either handle the unassigned case explicitly by using Int?, or, give it a default value:

let aString: Int
let aBool = true
if aBool {
aString = 2
} else {
aString = 0
}

print(aString)

How to safely unwrap optional variables in dart?

Your Dart example seems incomplete but it is difficult to say what is wrong without more context. If myString is a local variabel it will be promoted. You can see this example:

void main(){
myMethod(null); // NULL VALUE
myMethod('Some text'); // Non-null value: Some text
}

void myMethod(String? string) {
if (string != null) {
printWithoutNull(string);
} else {
print('NULL VALUE');
}
}

// Method which does not allow null as input
void printWithoutNull(String string) => print('Non-null value: $string');

It is a different story if we are talking about class variables. You can see more about that problem here: Dart null safety doesn't work with class fields

A solution to that problem is to copy the class variable into a local variable in your method and then promote the local variable with a null check.

In general, I will recommend reading the articles on the official Dart website about null safety: https://dart.dev/null-safety



Related Topics



Leave a reply



Submit