Creates a new instance from the given string.
SDK
- Xcode 9.0+
Framework
- Swift Standard Library
Declaration
init?<S>(_ text: S) where S : String Protocol
Parameters
textThe input string to convert to a
Doubleinstance. Iftexthas invalid characters or is in an invalid format, the result isnil.
Discussion
The string passed as text can represent a real number in decimal or hexadecimal format or special floating-point values for infinity and NaN (“not a number”).
The given string may begin with a plus or minus sign character (+ or -). The allowed formats for each of these representations is then as follows:
A decimal value contains the significand, a sequence of decimal digits that may include a decimal point.
let c = Double("-1.0") // c == -1.0 let d = Double("28.375") // d == 28.375A decimal value may also include an exponent following the significand, indicating the power of 10 by which the significand should be multiplied. If included, the exponent is separated by a single character,
eorE, and consists of an optional plus or minus sign character and a sequence of decimal digits.let e = Double("2837.5e-2") // e == 28.375A hexadecimal value contains the significand, either
0Xor0x, followed by a sequence of hexadecimal digits. The significand may include a decimal point.let f = Double("0x1c.6") // f == 28.375A hexadecimal value may also include an exponent following the significand, indicating the power of 2 by which the significand should be multiplied. If included, the exponent is separated by a single character,
porP, and consists of an optional plus or minus sign character and a sequence of decimal digits.let g = Double("0x1.c6p4") // g == 28.375A value of infinity contains one of the strings
"inf"or"infinity", case insensitive.let i = Double("inf") // i == Double.infinity let j = Double("-Infinity") // j == -Double.infinityA value of NaN contains the string
"nan", case insensitive.let n = Double("-nan") // n?.isNaN == true // n?.sign == .minusA NaN value may also include a payload in parentheses following the
"nan"keyword. The payload consists of a sequence of decimal digits, or the characters0Xor0xfollowed by a sequence of hexadecimal digits. If the payload contains any other characters, it is ignored. If the value of the payload is larger than can be stored as the payload of aDouble, the least significant bits are used..nan let p = Double("nan(0x10)") // p?.isNaN == true // String(p!) == "nan(0x10)"
Passing any other format or any additional characters as text results in nil. For example, the following conversions result in nil:
Double(" 5.0") // Includes whitespace
Double("±2.0") // Invalid character
Double("0x1.25e4") // Incorrect exponent format