string 在 Swift 3 中将数据转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40184468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Data to String in Swift 3
提问by IlyaGutnikov
I am very new to Swift.
我对 Swift 很陌生。
I want to create something like API on Swift for my educational app.
我想为我的教育应用程序在 Swift 上创建类似 API 的东西。
I have this code:
我有这个代码:
static func getFilm(filmID: Int) -> String {
print("getFilm")
let url = URL(string: "https://api.kinopoisk.cf/getFilm?filmID=\(filmID)")!
var request = URLRequest(url: url)
var returnData: String = ""
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if var responseVar = response, var dataVar = data {
print(responseVar)
returnData = String(data: dataVar, encoding: .utf8)
} else {
print(error)
}
}
task.resume()
return returnData
}
And I try to convert Data to String in this line: returnData = String(data: dataVar, encoding: .utf8)
我尝试在这一行中将数据转换为字符串: returnData = String(data: dataVar, encoding: .utf8)
Swift compiler gives me an error, and change this line to
returnData = String(data: dataVar, encoding: .utf8)!
, when I execute this line I get empty returnData variable.
Swift 编译器给了我一个错误,并将此行更改为
returnData = String(data: dataVar, encoding: .utf8)!
,当我执行此行时,我得到空的 returnData 变量。
If I use basic example line
print(String(data: data, encoding: .utf8))
everything will be OK and I can see data
in XCode console.
如果我使用基本示例行,
print(String(data: data, encoding: .utf8))
一切都会好起来的,我可以data
在 XCode 控制台中看到。
So, how I can convert Data to String?
那么,如何将数据转换为字符串?
回答by vadian
This is an example using a completion handler:
这是使用完成处理程序的示例:
class func getFilm(filmID: Int, completion: @escaping (String) -> ()) {
let url = URL(string: "https://api.kinopoisk.cf/getFilm?filmID=\(filmID)")!
URLSession.shared.dataTask(with:url) { (data, response, error) in
if error != nil {
print(error!)
completion("")
} else {
if let returnData = String(data: data!, encoding: .utf8) {
completion(returnData)
} else {
completion("")
}
}
}.resume()
}
And you call it
你叫它
MyClass.getFilm(filmID:12345) { result in
print(result)
}
In case of an error the completion handler returns an empty string.
如果出现错误,完成处理程序将返回一个空字符串。
MyClass
is the enclosing class of getFilm
method. Most likely the web service will return JSON, so you might need to deserialize the JSON to an array or dictionary.
MyClass
是getFilm
方法的封闭类。Web 服务很可能会返回 JSON,因此您可能需要将 JSON 反序列化为数组或字典。
In a more sophisticated version create an enum with two cases and associated values
在更复杂的版本中,创建一个包含两个案例和关联值的枚举
enum ConnectionResult {
case success(String), failure(Error)
}
With a little more effort demonstrating the subtle power of Swift you can return either the converted string on success of the error on failure in a single object.
通过更多的努力来展示 Swift 的微妙力量,您可以在单个对象中成功时返回转换后的字符串,失败时返回错误。
class func getFilm(filmID: Int, completion: @escaping (ConnectionResult) -> ()) {
let url = URL(string: "https://api.kinopoisk.cf/getFilm?filmID=\(filmID)")!
URLSession.shared.dataTask(with:url) { (data, response, error) in
if error != nil {
completion(.failure(error!))
} else {
if let returnData = String(data: data!, encoding: .utf8) {
completion(.success(returnData))
} else {
completion(.failure(NSError(domain: "myDomain", code: 9999, userInfo: [NSLocalizedDescriptionKey : "The data is not converible to 'String'"])))
}
}
}.resume()
}
On the caller side a switch
statement separates the cases.
在调用方,switch
语句将案例分开。
MyClass.getFilm(filmID:12345) { result in
switch result {
case .success(let string) : print(string)
case .failure(let error) : print(error)
}
}