Swift String Interpolation Displaying Optional

Swift String Interpolation displaying optional?

Optionals must be unwrapped. You must check for it or force unwrap as you do. Imagine the optional as a box where you put a value. Before you can access it, you need to put it out.

if let name = nameTextField.text {
nameLabel.text = "Hello, \(name)"
}

How do I prevent my text from displaying Optional() in the Swift interpolation?

I ended up going with the following because I didn't want to use guard, but I wanted to always display the message:

            var propertyNameStr = ""
if let propertyName = syncer!.getPropertyConfig()?.propertyName {
propertyNameStr = "from \(propertyName) "
}
messageText.text = "You can only switch properties once all images \(propertyNameStr)have finished uploading."

How to solve String interpolation produces a debug description for an optional value; did you mean to make this explicit? in Xcode 8.3 beta?

This is a change that was made in this pull request due to the fact that interpolating Optional(...) into the resultant string is often undesirable, and can be especially surprising in cases with implicitly unwrapped optionals. You can see the full discussion of this change on the mailing list here.

As mentioned in the pull request discussion (although unfortunately not by Xcode) – one slightly nicer way to silence the warning than the use of String(describing:) is to add a cast to the optional type of whatever you're interpolating, so for example:

var i: Int? = 5
var d: Double? = nil

print("description of i: \(i as Int?)") // description of i: Optional(5)
print("description of d: \(d as Double?)") // description of d: nil

Which can also be generalised to as Optional:

print("description of i: \(i as Optional)") // description of i: Optional(5)
print("description of d: \(d as Optional)") // description of d: nil

In Swift 5, with the new string interpolation system introduced by SE-0228, another option is to add a custom appendInterpolation overload for DefaultStringInterpolation:

extension DefaultStringInterpolation {
mutating func appendInterpolation<T>(optional: T?) {
appendInterpolation(String(describing: optional))
}
}

var i: Int? = 5
var d: Double? = nil

print("description of i: \(optional: i)") // description of i: Optional(5)
print("description of d: \(optional: d)") // description of d: nil

And, if desired, you could even remove the argument label to disable the warning entirely within a module (or within a particular file if you mark it as fileprivate):

extension DefaultStringInterpolation {
mutating func appendInterpolation<T>(_ optional: T?) {
appendInterpolation(String(describing: optional))
}
}

var i: Int? = 5
var d: Double? = nil

print("description of i: \(i)") // description of i: Optional(5)
print("description of d: \(d)") // description of d: nil

Though personally I would prefer to keep the argument label.

Remove optional keyword while displaying string - Swift

Replace this

releaseDateLabel.text = "\(releaseDateText): \(String(describing: date != "" ? Date.getMMMddyyyyDateFormat(date) : "\(tbaText)" ))"

with

releaseDateLabel.text = "\(releaseDateText): \(date != "" ? Date.getMMMddyyyyDateFormat(date)! : "\(tbaText)" ))

for safty try

if date != "" {
if let str = Date.getMMMddyyyyDateFormat(date) {
releaseDateLabel.text = "\(releaseDateText): \(str)"
}
}
else {
releaseDateLabel.text = "\(releaseDateText): \(tbaText)"
}

Swift String/Character Optional Printing without Optional

Here is function :

func firstNonRepeatingChar(input:String)->Character?{
//set a default return object
var result: Character? = nil
//convert input for easy and clean navigation
// let converted = Array(input) swift2
let converted = [Character](input.characters) //swift3
//set start of enumeration
var index: Int = 0
//set variable to compare
var c:Character
//should only trigger if non-empty input
while index<converted.count-1{
c=converted[index]
//check for non-repeated value
if !converted[index+1..<converted.count].contains(c){
result=c
return result
}
index+=1
}
return result
}

And calling :

print("The result is: \(firstNonRepeatingChar(input: "I miss you")?.description ?? "nil")")

output console :

The result is: I

or

 let fistString = "I miss you"  
print("here is FistString: \(fistString) and The result is: \(firstNonRepeatingChar(input: fistString)?.description ?? "nil")")

Why is my label displaying Your cat is Optional(35) years old when it should display Your cat is 35 years old?

The problem is here:

String(describing: catYears)

catYears is an Optional<Int>, a string that describes an Optional<Int> will be in the format of Optional(<value>) or nil. That's why you get Optional(35).

You need to unwrap catYears!

String(describing: catYears!)

Or, remove String(describing:) all together and do:

if let humanYearsText = getHumanYears.text, let humanYears = Int(humanYearsText)
{
let catYears = humanYears * 7
displayCatYears.text = "Your cat is \(catYears) years old"
}

Is there a Swifty way to unwrap optionals with string interpolation?

In Swift 5 you can extend String.StringInterpolation and write custom interpolations. Read More

extension String.StringInterpolation {
public mutating func appendInterpolation<T>(if value: T?, _ literal: StringLiteralType) {
if let value = value {
appendInterpolation(literal+"\(value)")
}
}
}

Now instead of

let startTime = parms.startDate != nil ? "&starttime=\(parms.startDate!)" : ""

You can use

let startTime = "\(if: parms.startDate, "&starttime=")"

Usage

var startTime = "\(if: parms.startDate, "&starttime=")"
print(startTime)//""
parms.startDate = "mytime"
startTime = "\(if: parms.startDate, "&starttime=")"
print(startTime)//"""&starttime=mytime"

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

Warnings from String interpolation

So, the first suggested fix worked for you. It quieted the compile time warning, although admittedly String(describing:) is a weak solution.

In both cases, you need to unwrap the optional value. For the first case you should use:

guard let selectedMealCell = sender as? MealTableViewCell else {
if let sender = sender {
fatalError("Unexpected sender: \(sender))")
} else {
fatalError("sender is nil")
}
}

and in the second case:

fatalError("Unexpected Segue Identifier; \(segue.identifier ?? "")")

Then you got a runtime error:

"Unexpected Segue Identifier;"

That is telling you that your switch didn't match the first 2 cases and it ran the default case. The crash is caused because your code is explicitly calling fatalError. Your segue.identifier is apparently an empty string.

So your problem is actually in your Storyboard. You need to assign identifiers to your segues. Click on the segue arrows between your view controllers, and assign identifiers "AddItem" and "ShowDetail" to the proper segues. The segue identifier is assigned in the Attributes Inspector on the right in Xcode.

Swift: Provide default value inside string literal

Just wrap it in parentheses:

print("Error \((response.result.error ?? "default value"))")

The cleaner way is to use @Alladinian answer and put the string in a variable before printing it



Related Topics



Leave a reply



Submit