I am trying to convert an Int16 value to String but it gives value with Optional, won't allow me to forced unwrap it.
String(describing:intValue) Result : Optional(intValue)
Unwrap intValue first, then pass it to the string initializer: String(unwrappedIntValue)
Here are some ways of handling the optional. I've added explicit string# variables with type annotations, to make it clear what types are involved
let optionalInt: Int? = 1 // Example 1 // some case: print the value within `optionalInt` as a String // nil case: "optionalInt was nil" if let int = optionalInt { let string1: String = String(int) print(string1) } else { print("optionalInt was nil") } // Example 2, use the nil-coalescing operator (??) to provide a default value // some case: print the value within `optionalInt` as a String // nil case: print the default value, 123 let string2: String = String(optionalInt ?? 123) print(string2) // Example 3, use Optional.map to convert optionalInt to a String only when there is a value // some case: print the value within `optionalInt` as a String // nil case: print `nil` let string3: String? = optionalInt.map(String.init) print(string3 as Any) // Optionally, combine it with the nil-coalescing operator (??) to provide a default string value // for when the map function encounters nil: // some case: print the value within `optionalInt` as a String // nil case: print the default string value "optionalInt was nil" let string4: String = optionalInt.map(String.init) ?? "optionalInt was nil" print(string4) String(intValue) (without the describing:)?You can convert a number to a String with string interpolation:
let stringValue = "\(intValue)" Or you can use a standard String initializer:
let stringValue = String(intValue) If the number is an Optional, just unwrap it first:
let optionalNumber: Int? = 15 if let unwrappedNumber = optionalNumber { let stringValue = "\(unwrappedNumber)" } Or
if let unwrappedNumber = optionalNumber { let stringValue = String(unwrappedNumber) } intValue is an optional, this will have the same issue as String(describing:).String(int)if let intValue = intValue {
String(describing:)to convert any value to a string that will be shown to the user.