Converting NSData to Integer in Swift

后端 未结 7 2081
予麋鹿
予麋鹿 2021-01-05 02:29

In Objective-C the code looked liked this and worked flawlessly,

NSInteger random = arc4random_uniform(99) + 1 
NSData *data = [NSData dataWithBytes:& ra         


        
7条回答
  •  时光说笑
    2021-01-05 03:14

    My contribution with a swift 3.1 extension :

    extension NSData{
        var int :  Int{
            var out: Int = 0
            self.getBytes(&out, length: MemoryLayout.size)
            return out
        }
    }
    

    Just call .int to get your value, just like this :

    let value = 50
    let data = NSData(bytes: &value, length: 4)
    print(data.int)
    

提交回复
热议问题