Swift-为什么String转换Int的结果是nil

摘要

知其然,更要知其所以然。前段时间用 String 转换 Int 处理时,发现一种情况返回 nil,就换成 String 转换 Double 的方式处理。今天就要来看看这种返回 nil 的情况是怎么造成的。

当有小数的 String 文本转换为 Int 类型时,返回的值并不是咱们想要的向下取整后的整数,而是 nil。

// Int 转换为 String
let intStr = "2.78"
let int = Int(intStr) // nil

为什么是nil?今天就来解解这个疑惑。

String 转换 Int 本质

首先com+鼠标左键弹出选项,选择jump to Definition(跳转到定义)一波操作,来到 Int 的定义地方,直接全局搜索一下 String,直接看下定义。

    /// Creates a new integer value from the given string.
    ///
    /// The string passed as `description` may begin with a plus or minus sign
    /// character (`+` or `-`), followed by one or more numeric digits (`0-9`).
    ///
    ///     let x = Int("123")
    ///     // x == 123
    ///
    /// If `description` is in an invalid format, or if the value it denotes in
    /// base 10 is not representable, the result is `nil`. For example, the
    /// following conversions result in `nil`:
    ///
    ///     Int(" 100")                       // Includes whitespace
    ///     Int("21-50")                      // Invalid format
    ///     Int("ff6600")                     // Characters out of bounds
    ///     Int("10000000000000000000000000") // Out of range
    ///
    /// - Parameter description: The ASCII representation of a number.
    @inlinable public init?(_ description: String)

出处找到了,不想费力看注释的,直接看我给的结论:

String 转换为 Int 类型,传入 Int 的 description 参数,必须是一个或者多个0-9组合的整数,整数前可以加“+”或者“-”。通俗说,这个 text 文本必须是一个整数。否则都返回 nil。

看到现在,大致可以明白了Int("2.78")为什么是 nil。

String 转换 Double 本质

看完String 转换 Double 本质后,顺势也看下String 转换 Double 本质。同样的查找逻辑一波操作,找到它的定义

extension Double : LosslessStringConvertible {

    /// Creates a new instance from the given string.
    ///
    /// 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.375
    ///
    /// 此处省略 57 行注释------------------
    ///
    /// - Parameter text: The input string to convert to a `Double` instance. If
    ///   `text` has invalid characters or is in an invalid format, the result
    ///   is `nil`.
    @inlinable public init?<S>(_ text: S) where S : StringProtocol

    @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
    public init?(_ text: Substring)
}

Double(string)中的 string 文本可以是一个10进制、16进制或者浮点数的(这个非常关键)。也可以添加“+”,“-”符号。

这里简单总结一下,Double 转换为 text,并保留几位小数的处理方法,加深一些印象

let double = Double(2.7895)
// double 转换为 String
print("\(double)") // 输出 "2.7895"

// 保留两位小数
print(String(format:"%.2f", double) // 输出 "2.79"

Int("2.78") 怎么处理,不是 nil?

看完了上面两个转换的定义之后,那么是否可以组合一下,解决可能出现的 nil?那是当然。

首先将文本转换为 Double,然后将 Double 转换为 Int

Int(Double("2.78")!) // 2

Double 转换 Int

代码验证没有问题,那么就看看,Double 转换 Int 做了什么事情。


    /// Creates an integer from the given floating-point value, rounding toward
    /// zero.
    ///
    /// Any fractional part of the value passed as `source` is removed, rounding
    /// the value toward zero.
    ///
    ///     let x = Int(21.5)
    ///     // x == 21
    ///     let y = Int(-21.5)
    ///     // y == -21
    ///
    /// - Parameter source: A floating-point value to convert to an integer.
    ///   `source` must be representable in this type after rounding toward
    ///   zero.
    public init(_ source: Double)

定义中可以看到,Double 类型的数据,经过 Int 转换后,会生成一个只保留整数的数(小数部分略去)。所以也就支持了上节部分的处理方式。

Double 类型整数省略 .000

在看 Double 转换 Int定义时,无意间发现一个好玩的定义,先上定义


    /// Creates an integer from the given floating-point value, if it can be
    /// represented exactly.
    ///
    /// If the value passed as `source` is not representable exactly, the result
    /// is `nil`. In the following example, the constant `x` is successfully
    /// created from a value of `21.0`, while the attempt to initialize the
    /// constant `y` from `21.5` fails:
    ///
    ///     let x = Int(exactly: 21.0)
    ///     // x == Optional(21)
    ///     let y = Int(exactly: 21.5)
    ///     // y == nil
    ///
    /// - Parameter source: A floating-point value to convert to an integer.
    public init?(exactly source: Double)

定义说明,可以将一个精确标示的浮点数转换为 Int 类型。这里的精确标示就是没有小数的值。有了这个定义,那么岂不是可以解决某一个应用场景了吗?

显示存在需要保留2位小数的文本时,当浮点数是一个没有小数的数值,那么就显示整数。

// old
String(format: "%.2f", 2.578) // 2.58
String(format: "%.2f", 2.0) // 2.00

// new
if Int(exactly: 2.00) != nil {
    "\(Int(exactly: 2.00)!)" // 2
}

题外话

感谢看到这里,感觉有一点收获,给个小赞。有分析的不到位,评论区留言帮我梳理。

偶尔有一些想要搞清楚的问题,评论区告诉我,咱们一起解决。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 228,546评论 6 533
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 98,570评论 3 418
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 176,505评论 0 376
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,017评论 1 313
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 71,786评论 6 410
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 55,219评论 1 324
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,287评论 3 441
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,438评论 0 288
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 48,971评论 1 335
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,796评论 3 354
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 42,995评论 1 369
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,540评论 5 359
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,230评论 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 34,662评论 0 26
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 35,918评论 1 286
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 51,697评论 3 392
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 47,991评论 2 374

推荐阅读更多精彩内容