Numbers and Strings

Swift Strings: Numbers and Strings

Use string interpolation to mix numbers with text.

Convert numbers to strings explicitly with String(value) when concatenating.


Mix Text and Numbers

Use interpolation to embed numbers directly in strings, or convert numbers with String(value) when concatenating.

Example

let age = 5
print("Age: \(age)")          // interpolation
let text = "You are " + String(age)
print(text)
let pi = 3.14
print("pi = \(pi)")

This example shows interpolation and explicit conversion with String().



Convert String to Number

Use numeric initializers like Int("123") which return optionals because conversion can fail.

Example

let s1 = "123"
let n1 = Int(s1)           // Int?
print(n1 ?? 0)

let s2 = "abc"
let n2 = Int(s2)           // nil (not a number)
print(n2 == nil)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *