1

Maybe a very basic question, but haven't found a good answer without a lot of extra code basically:

var item: String?
print(item) //works as expected
print("Item: "+item) //compile error

I'd like to achieve the second form without extra variables or expressions/code in some way?

breakline
  • 5,776
  • 8
  • 45
  • 84

3 Answers3

3

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

Bhavin Kansagara
  • 2,866
  • 1
  • 16
  • 20
1

I'd reccommend using string interpolation.

You have 4 options for actually unwrapping the optional:

  1. Checking against nil. You can make sure that your optional is non-nil, and if so, force-unwrap it.

    if optional != nil {
        print(optional!)
    }
    
  2. if-let or guard-let (optional binding). This checks to see if the optional is non-nil, and if so, provides it, unwrapped, inside the if statement.

    if let nonOptional = optional {
        print(nonOptional)
    }
    
  3. Force-unwrapping. This acts normally if your optional is not nil, but crashes if it is nil. For that reason, this approach is not recommended.

    print(optional!)
    
  4. Default values. This approach uses the value of your variable if it is non-nil, or the provided default value if it was nil.

    print(optional ?? "Optional was nil!")
    

For your specific scenario, I would either this:

print("Item: \(item ?? "Item was nil!")")

or this:

if let item = item {
    print("Item: \(item)")
} else {
    print("Item was nil!")
}

Keep in mind that you don't need an else clause if you don't want to print if item is nil.

Hope this helps!

Sam
  • 2,350
  • 1
  • 11
  • 22
0

try the following line

if let item = item {
    print(String.init(format: "Item: %@", item))
}

or

if let item = item {
   print("Item: \(item)") 
}
VishalPethani
  • 854
  • 1
  • 9
  • 17