【问题标题】:Swift Convert Optional String to Int or Int32 (Unwrapping optionals question)Swift Convert Optional String to Int or Int32 (Unwrapping optionals question)
【发布时间】:2019-06-15 06:46:44
【问题描述】:

我正在尝试读取字符串并将其转换为 int。我有一个解决方案,但它似乎太复杂了。我想我仍在努力解开包装。

我在下面发布了代码以及我在每个解决方案中遇到的编译器错误。

在本例中,我尝试从 UserDefaults 中读取字符串并转换为整数值。

static func GetSelectedSessionNum() -> Int32 {
    var sessionNum : Int32 = 0
    let defaults = UserDefaults.standard

    let optionalString: String? = defaults.string(forKey: "selectedSessionNum")
    // this works but it's too complicated
    if let string = optionalString, let myInt = Int32(string) {
        return myInt
    }
    return 0

    // Error : optional String? must be unwrapped to a value of type 'String'
    let t : String = defaults.string(forKey: "selectedSessionNum")

    if let s : String = defaults.string(forKey: "selectedSessionNum") {
        // error - Int32? must be unwrapped to a value of Int32
        return Int32(s)
    }
    return 0
}

【问题讨论】:

  • 您的工作解决方案并不复杂。这是正确的方法。你有两个选项要处理。顺便说一句 - 为什么将会话编号存储为字符串而不是将其存储为实际数字?这会让事情变得更简单。

标签: swift optional forced-unwrapping


【解决方案1】:

您需要强制转换为 non optional Int32 以匹配您的返回类型。

您可以使用任何可选的绑定方法,或将返回类型更改为Int32?

【讨论】:

    【解决方案2】:

    如果您想要一个简单的解决方案,请将selectedSessionNum 保存为Int

    static func getSelectedSessionNum() -> Int32 {    
        return Int32(UserDefaults.standard.integer(forKey: "selectedSessionNum"))
    }
    

    否则双重可选绑定

    if let string = UserDefaults.standard.string(forKey: "selectedSessionNum"), let myInt = Int32(string) {
        return myInt
    }
    

    或 nil 合并运算符

    if let string = UserDefaults.standard.string(forKey: "selectedSessionNum") {
        return Int32(string) ?? 0
    }
    

    是正确的方法

    【讨论】:

    • OP 可能没有充分的理由使用 Int32。从标题 String to Int or Int32 (Unwrapping optionals question)
    • 如果可能,integer(forKey:) 甚至会将字符串首选项转换为整数。
    • @MartinR 不知道。如果不可能,它会返回什么? 0?
    • 文档说 表示整数的字符串变成等效整数(例如“123”变成 123)。 – 如果字符串不表示整数,则为 0被退回。
    【解决方案3】:

    如果您想避免可选绑定,可以使用flatMap,当在Optional 上调用时,它允许您将一个可选绑定转换为另一个:

    return UserDefaults.standard.string(forKey: "selectedSessionNum").flatMap(Int32.init) ?? 0
    

    您还需要??(nil 合并运算符)来涵盖初始化程序失败或用户默认值中不存在该值的情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-15
      • 2022-12-26
      • 2022-12-16
      • 2013-10-10
      • 1970-01-01
      • 2013-09-09
      • 1970-01-01
      相关资源
      最近更新 更多