Convert Int to String in Swift
Converting Int
to String
:
let x : Int = 42
var myString = String(x)
And the other way around - converting String
to Int
:
let myString : String = "42"
let x: Int? = myString.toInt()
if (x != nil) {
// Successfully converted String to Int
}
Or if you're using Swift 2 or 3:
let x: Int? = Int(myString)
swift How to cast from Int? to String
You can use string interpolation.
let x = 100
let str = "\(x)"
if x
is an optional you can use optional binding
var str = ""
if let v = x {
str = "\(v)"
}
println(str)
if you are sure that x
will never be nil
, you can do a forced unwrapping
on an optional value
.
var str = "\(x!)"
In a single statement you can try this
let str = x != nil ? "\(x!)" : ""
Based on @RealMae's comment, you can further shorten this code using the nil coalescing operator (??)
let str = x ?? ""
Converting Int to String in Swift
String cannot init with Int?, but it can with Int. Since String(int:Int) doesn't return an optional, you can get the effect you want with the same amount of code:
if let _duration = duration {
viewDuration = String(_duration)
} else {
viewDuration = ""
}
Cast Int? to a String in a Text Component
some examples, first unwrapping Int with default option
Text("\(workDuration ?? 0)")
Second case not to show a default text, and not to draw object Text (paddings, modifiers associates)
if let workDuration != nil { Text("\(workDuration ?? 0)") }
Third more elegant as suggested by George, same as second option
if let workDuration = workDuration { Text("\(workDuration)") }
Four, following Rob Napier's comment, unwrapping your model
struct Workout {
var duration: Int?
var durationDescription : String {
"\(duration ?? 0)"
}
}
struct ContentView: View {
let workout = Workout(duration: 33) //sample
var body: some View {
Text("\(workout.durationDescription)")
}
}
Casting an Int as a String from a Realm result Swift
The issue isn't String(lastRecord?.time)
being Optional
. The issue is lastRecord
being Optional
, so you have to unwrap lastRecord
, not the return value of String(lastRecord?.time)
.
if let lastRecord = lastRecord {
previousRoundsLabel.text = "\(lastRecord.time)"
}
How to convert an Int to a Character in Swift
You can't convert an integer directly to a Character
instance, but you can go from integer to UnicodeScalar
to Character
and back again:
let startingValue = Int(("A" as UnicodeScalar).value) // 65
for i in 0 ..< 26 {
print(Character(UnicodeScalar(i + startingValue)))
}
Convert Int to String while decoding JSON in Swift
You can try
struct Person: Decodable {
let name,age: String
private enum CodingKeys : String, CodingKey {
case name, age
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
do {
let years = try container.decode([String:Int].self, forKey: .age)
age = "\(years["age_years"] ?? 0)"
}
catch {
let years = try container.decode([String:String].self, forKey: .age)
age = years["age_years"] ?? "0"
}
}
}
Swift simplify optional Int to String conversion with nil coalescing operator
Here's one solution:
let str = "\(num.map { String($0) } ?? "?") foo"
This returns "? foo"
if num
is nil
or it returns "42 foo"
if num
is set to 42
.
Related Topics
Class Level or Struct Level Method in Swift Like Static Method in Java
Should Iboutlet Be Weak or Strong Var
How to Call Initializer for Subclass of Generic Type
Swift + Nsviewcontroller Background Color (MAC App)
Swift Optional Escaping Closure
Ios-Charts Library: X-Axis Labels Without Backing Data Not Showing
The Correct Way to Override an Initializer in Swift 1.1
Why Is My Swift Loop Failing with Error "Can't Form Range with End < Start"
Using Environmentobject in Watchos
One-Way Platform Collisions in Sprite Kit
Where to Get Frame Size of Custom Uiview in Its Subclass
How to Save Cgimage to Data in Swift
How to Use Swift Package Manager in Xcode 9 Playground
Uicollectionviewcell Register Class Fails, But Register Nib Works
How to Get the Yaw, Pitch, Roll of an Aranchor in Absolute Terms