[英]how to convert Data to Int in swift
I'm coding in Swift.我正在用 Swift 编码。 API returns a Data which need to be converted to Int! API 返回一个需要转换为 Int 的 Data! what should I do?我该怎么办?
the response that I need looks like::我需要的回应看起来像::
12345 12345
but the think I get when I print data is :但是当我打印数据时我得到的想法是:
Optional(5 bytes)可选(5 个字节)
API returns an Int (not JSON) API 返回一个 Int(不是 JSON)
//send HTTP req to register user
let myUrl = URL(string: "http://app.avatejaratsaba1.com/api/Person/Create")
var request = URLRequest(url: myUrl!)
request.httpMethod = "POST" // compose a query string
request.addValue("application/json", forHTTPHeaderField: "content-type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let postString = ["name" : name.text!,
"isLegal" : FinalLegalSegment,
"codeMelli" : National_ID.text! ] as [String : Any]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted)
}catch let error {
print(error.localizedDescription)
self.DisplayMessage(UserMessage: "1Something went wrong , please try again!")
return
}
let task = URLSession.shared.dataTask(with: request)
{
(data : Data? , response : URLResponse? , error : Error?) in
self.removeActivtyIndicator(activityIndicator: MyActivityIndicator)
if error != nil
{
self.DisplayMessage(UserMessage: "2Could not successfully perform this request , please try again later.")
print("error = \(String(describing : error))")
return
}
else
{
print("////////////////////////////////")
print("data has been sent")
}
}
task.resume()
one can use withUnsafeBytes to get the pointer and load the integer可以使用 withUnsafeBytes 来获取指针并加载整数
let x = data.withUnsafeBytes({
(rawPtr: UnsafeRawBufferPointer) in
return rawPtr.load(as: Int32.self)
})
rawPtr is unsaferawbufferpointer and the load() helps to return the value to x. rawPtr 是 unsaferawbufferpointer 并且 load() 有助于将值返回给 x。 This can be used for getting any integer.这可用于获取任何整数。 The rawPtr is a temporary pointer and it must not be used outside the block. rawPtr 是一个临时指针,不能在块外使用。
This is available since Swift 5 and the older version had这是可用的,因为 Swift 5 和旧版本有
public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType
which is deprecated.已弃用。
first convert your data into string like blow and then use that string to initialize int首先将您的数据转换为像打击这样的字符串,然后使用该字符串来初始化 int
let stringInt = String.init(data: yourdata, encoding: String.Encoding.utf8)
let int = Int.init(stringInt ?? "")
this will return an optional value which you can unwrap to use further这将返回一个可选值,您可以打开它以进一步使用
As I wrote in my comment, your server sends text representation of an integer.正如我在评论中所写,您的服务器发送一个整数的文本表示。
You need to write something like this:你需要写这样的东西:
if error != nil
{
//...
return
}
else
{
if let data = data {
//First convert the data into String
if let text = String(data: data, encoding: .utf8) {
//And then into Int
if let value = Int(text) {
print(value)
//... use the value
} else {
print("text cannot be converted to Int")
}
} else {
print("data is not in UTF-8")
}
} else {
print("data == nil")
}
}
The code above might be simpler, if you do not need some print
s.如果您不需要一些print
,上面的代码可能会更简单。
Using guard
as suggested by Martin R, the code above looks something like this:使用 Martin R 建议的guard
,上面的代码看起来像这样:
guard let data = data else {
print("data == nil")
return
}
guard let text = String(data: data, encoding: .utf8) else {
print("data is not in UTF-8")
return
}
guard let value = Int(text) else {
print("text cannot be converted to Int")
return
}
print(value)
//... use the value
You can avoid deeply nested code using guard
.您可以使用guard
避免深度嵌套的代码。 (You can use guard
for checking error != nil
, but I leave that for you.) (你可以使用guard
来检查error != nil
,但我把它留给你。)
try this:尝试这个:
let intValue: Int = yourData.withUnsafeBytes { $0.pointee }
withUnsafeBytes { $0.pointee }
will return a generic type, you can cast it to your known type. withUnsafeBytes { $0.pointee }
将返回一个泛型类型,您可以将其转换为您已知的类型。
Swift 5斯威夫特 5
You can use count
like this:您可以像这样使用count
:
print(data!.count)
让 dataString = data.data(using: .utf8, allowLossyConversion: false).debugDescription dataInt = (Int)(dataString)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.