Senseful
Senseful

Reputation: 91911

Difference between String(int) and int.description in Swift?

I understand the difference between String(describing: int) and String(int).

However, I'm not sure what the difference is between String(int), and int.description (or even "\(int)" for that matter).

Are these functions always going to return the same value?

let int: Int = 123
let string1 = String(int)
let string2 = int.description
assert(string1 == string2)

In this simple example, it shows they are the same, but I'm wondering if there are ever times they may be different, or if there are other reasons I may want to avoid one or the other.

I see String(int) being used a lot, but the other version is slightly easier to use on Int? values:

let optionalString = optionalInt?.description

Upvotes: 1

Views: 549

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236528

The difference is that you shouldn't use description method. Note that for integers the description result will probably never change but for other types there is no guarantee. For example Data used to have a different description a few years ago. Btw if you use String(describing: optionalInt) or string interpolation of optionalInt it will result in Optional("whatever")

Resuming usage of the description method is discouraged. Check CustomStringConvertible description If you want you can create a computed property you can extend LosslessStringConvertible and create a string property. It will allow you to use will all types that conform to it:

extension LosslessStringConvertible {
    var string: String { .init(self) }
}

Usage:

1.string     // "1"
2.5.string   // "2.5"

Upvotes: 2

Related Questions