Richard Topchii
Richard Topchii

Reputation: 8185

String initializer for optional primitive types: Int? Double? Float? etc

Is it possible to have an extension for all of the above types without specifying each type individually?

For example, here is such extension for Double:

extension String {
  init?(_ value: Double?) {
    if let nonOpt = value {
      self.init(nonOpt)
    } else {
      return nil
    }
  }
}


let nonOpt: Double = 1

let opt: Double? = 1

let string = String(opt)

print(string)

I'd like to allow string initialization with optional type if it is possible to initialize string with the original type.

Upvotes: 1

Views: 2146

Answers (2)

vadian
vadian

Reputation: 285092

Do you mean something like this

extension String {
    init?<T : CustomStringConvertible>(_ value : T?) {
        guard let value = value else { return nil }
        self.init(describing: value)
    }
}

or

extension String {
    init?<T : LosslessStringConvertible>(_ value : T?) {
        guard let value = value else { return nil }
        self.init(value)
    }
}

Upvotes: 6

Andy Obusek
Andy Obusek

Reputation: 12842

Rather than declaring an custom initializer, just use map to map the value to a String as such:

let optDouble: Double? = nil
let optionalDoubleString = opt.map { String($0) }
let optInt: Int? = nil
let optionalIntString = opt.map { String($0) }

Upvotes: 3

Related Questions