简体   繁体   中英

Convert Int16 to String Swift 4

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)

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM