Convert Int to UInt32 in Swift

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

Here is a sample of what I’m trying to do.:

  • NSNumberFormatter numberFromString is adding a small fraction when converting certain numbers
  • How can I declare a variable in Swift using the type defined in an AnyClass object?
  • Usage of withMemoryRebound with Apples Swift 3 beta 6
  • How can I convert an array to a tuple?
  • how can i pass an int value through a selector method?
  • Swift: How to convert String to UInt?
  • func initNetwork(IP: String, Port: Int) {
        // relevant stuff
    
        //Convert Port:Int to UInt32 to make this shit work!
    
        CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, IP as NSString , Port , &readStream, &writeStream)
    
        // Irelevant stuff
    }
    

    I have been looking around for a solution for some time now, and i can’t seem to find one!

    4 Solutions Collect From Internet About “Convert Int to UInt32 in Swift”

    You can do it easily:

    var x = UInt32(yourInt)
    

    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)
    

    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

    Still more easier: (Wondering why they use the unsigned func)

    var x = Int32(yourInt)