0

我正在尝试读取一个字符串并将其转换为一个 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
}
4

3 回答 3

0

如果您想要一个简单的解决方案另存selectedSessionNumInt

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
}

是正确的方法

于 2019-01-21T20:43:55.560 回答
0

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

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

于 2019-01-21T20:38:08.020 回答
0

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

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

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

于 2019-01-21T21:53:41.953 回答