Swift5でDataをString、Int、Float、Double、NSNumberに変換する方法
DataをString(文字列)、Int(数値)、Float(整数)、Double、NSNumber、NSDataへ変換する方法をまとめました。
Data ←→ String
Data → String
var data : Data = "あいうえお".data(using: String.Encoding.utf8)!
var str : String = String.init(data: data, encoding: .utf8)!
String → Data
var str : String = "あいうえお"
var data : Data = str.data(using: String.Encoding.utf8)!
Data ←→ Int
Data → Int
var data : Data = "1234".data(using: .utf8)!
var str : String = String.init(data: data, encoding: .utf8)!
var num : Int = Int(str)!
Int → Data
var intNum : Int = 1234
var str : String = String(intNum)
var data : Data = str.data(using: .utf8)!
Data ←→ Float
Data → Float
var data : Data = "1.2345678".data(using: .utf8)!
var str : String = String.init(data: data, encoding: .utf8)!
var floatNum : Float = Float(str)!
Float → Data
var floatNum : Float = 1.2345678
var str : String = String(floatNum)
var data : Data = str.data(using: .utf8)!
Data ←→ Double
Data → Double
var doubleNum : Double = 1.2345678
var str : String = String(dobleNum)
var data : Data = str.data(using: .utf8)!
Double → Data
var data : Data = "1.2345678".data(using: .utf8)!
var str : String = String.init(data: data, encoding: .utf8)!
var doubleNum : Double = Double(str)!
Data ←→ NSNumber
Data → NSNumber
var data : Data = "1.2345678".data(using: String.Encoding.utf8)!
var str : String = String.init(data: data, encoding: .utf8)!
var nsstring : NSString = NSString(string: str)
var doubleNum : Double = nsstring.doubleValue
var num : NSNumber = NSNumber.init(value: doubleNum )
Data → NSNumber
var num : NSNumber = NSNumber.init(value: 1.2345678 )
var str = String(num.doubleValue)
var data : Data = str.data(using: String.Encoding.utf8)!
Data ←→ NSData
Data → NSData
var data : Data = "1.2345678".data(using: String.Encoding.utf8)!
var nsdata : NSData = NSData.init(data: data)
NSData → Data
var data1 : Data = "1.2345678".data(using: String.Encoding.utf8)!
var nsdata : NSData = NSData.init(data: data1)
var data2 : Data = nsdata as Data