如何从可选的Int初始化可选的UInt?

ami*_*mir 2 type-conversion optional swift

我想将可选的Int转换为可选的UInt:

let optionalNumber : Int?
//later in code
let optionalPositiveNumber = UInt(optionalNumber)
Run Code Online (Sandbox Code Playgroud)

给出错误:

Cannot invoke initializer for type 'Uint' with an argument list of type (Int?)
Run Code Online (Sandbox Code Playgroud)

我可以通过为UInt创建以下扩展来解决这个问题:

extension UInt {
   init?(_ number : Int?) {
       if let number = number {
           self = UInt(number)
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法转换Int?UInt?不使用扩展或条件检查(如果,保护)?

Mar*_*n R 6

你可以map选择:

var optionalNumber : Int?

//later in code
let optionalPositiveNumber = optionalNumber.map { UInt($0) }
Run Code Online (Sandbox Code Playgroud)

文档:

当此Optional实例不为nil时,计算给定的闭包,将未包装的值作为参数传递.

func map<U>(_ transform: (Wrapped) throws -> U) rethrows -> U?

因此,结果是UInt?按要求,并且是nil转换的签名号码.

请注意,如果给定的数字为负数,则转换将失败(并且会因运行时异常而崩溃).如果这是一个问题,可能会有更好的变体

let optionalPositiveNumber = optionalNumber.flatMap { UInt(exactly: $0) }
Run Code Online (Sandbox Code Playgroud)

nil如果给定的数字是nil负数,则返回.