Convert Int to UInt32 in Swift

前端 未结 3 1442
悲&欢浪女
悲&欢浪女 2021-02-11 13:33

Im making a Tcp client and therefore using the CFStreamCreatePairWithSocketToHost which is expecting an UInt32 for the second parameter.

Here is a sample of

相关标签:
3条回答
  • 2021-02-11 13:45

    It's very simple:

    let int: Int = 40
    let uint = UInt32(i)
    

    in your case, just pass

    UInt32(Port)
    

    For a port is not a problem, but in other cases be sure to take care of overflow

    Side note: in swift it's good practice to name variables using lower camel case, so with the first letter in lowercase

    0 讨论(0)
  • You can do it easily:

    var x = UInt32(yourInt)
    
    0 讨论(0)
  • 2021-02-11 14:01

    Nikos M.'s answer might overflow because Swift Ints are 64 bit now, and Swift will crash when the default UInt32 initializer overflows. If you want to avoid overflow, use the truncatingBitPattern initializer.

    If you're sure your data won't overflow, then you should use the default initializer because an overflow represents invalid data for your application. If you're sure your data will overflow, but you don't care about truncation (like if you're building hash values or something) then you probably want to truncate.

    let myInt: Int = 576460752303423504
    let myUInt32 = UInt32(truncatingBitPattern: myInt)
    
    0 讨论(0)
提交回复
热议问题