如何解包一个Optional值?

时间:2016-12-01 12:19:33

标签: swift3 xcode7 optional uint32 uint

所以我的代码中有这个。

let hex:String = "#FFFFFF"
var returnValue = UInt()
var newString = String()

newString = hex.replacingOccurrences(of: "#", with: "0x")
returnValue = UInt(newString)! //This line gets an error

它为我提供了一个解包可选值错误。我该如何解决?

1 个答案:

答案 0 :(得分:0)

您使用了错误的初始化程序,即使它是正确的初始化程序,字符串格式也是错误的:

let hex = "#FFFFFF"
let newString = hex.replacingOccurrences(of: "#", with: "")
let returnValue = UInt(newString, radix:16) ?? 0