Check if string is a valid double value in Swift

edit/update: Xcode 11 or later • Swift 5.1 or later

You can use Double initializer init?<S>(_ text: S) where S : StringProtocol to create an instance property on StringProtocol and use it to check if a String or Substring is a valid Double:

extension StringProtocol {
    var double: Double? { Double(self) }
    var float: Float? { Float(self) }
    var integer: Int? { Int(self) }
}

Testing

let str = "2.9"
if let value = str.double  {
    print(value)           // "2.9\n"
} else {
    print("invalid input")
}

str.prefix(1).integer  // 2
str.suffix(1).integer  // 9

It is indeed more efficient not to create a number formatter every time we do a conversion:

extension String {
     struct NumFormatter {
         static let instance = NumberFormatter()
     }

     var doubleValue: Double? {
         return NumFormatter.instance.number(from: self)?.doubleValue
     }

     var integerValue: Int? {
         return NumFormatter.instance.number(from: self)?.intValue
     }
}

Why not let it return false? Or true of course.

extension String {

    func isInt() -> Bool {

        if let intValue = Int(self) {
            return true
        }

        return false
    }

    func isFloat() -> Bool {

        if let floatValue = Float(self) {
            return true
        }

        return false
    }

    func isDouble() -> Bool {

        if let doubleValue = Double(self) {
            return true
        }

        return false
    }

    func numberOfCharacters() -> Int {
        return self.characters.count
    }
}

Or even better, as suggested by @LeoDabus:

extension String {
    var isInteger: Bool { return Int(self) != nil }
    var isFloat: Bool { return Float(self) != nil }
    var isDouble: Bool { return Double(self) != nil }
}