我有一个函数从服务器获取一个文件并解析了该文件,我正在使用一个具有如下完成处理程序的函数来获取该文件
func getMachineDetails(completionHandler: @escaping ([MachineDetails]? , Error?) -> Void) {
var details = [MachineDetails]()
let url = URL(string: "https://somefile.txt")!
let task = URLSession.shared.downloadTask(with: url) { (urlOrnil, responseOrNil, errorOrNil) in
guard let fileURL = urlOrnil else { return }
do {
guard let contents = try? String(contentsOf: fileURL) else { throw errorOrNil! }
let lines = contents.split(separator: "\n")
for line in lines {
let entries = line.split(separator: ";").map { String($0) }
if entries.count == 4 {
let newMachine = MachineDetails(machineNumber:entries[0],
machineName:entries[1],
machineXML:entries[2],
machineWiFi:entries[3])
details.append(newMachine)
} else {
print("Malformed line \(line)")
}
}
} catch {
print("file error: \(error)")
}
}
task.resume()
print(details)
completionHandler(details, nil)
}
但是,当我尝试使用该函数时
func getMachineName(machineNumber: String) -> String {
getMachineDetails { (machineDetails, error) in
if let machineDetails = machineDetails {
let index = machineDetails.firstIndex { $0.machineNumber == machineNumber }
return machineDetails[index].machineName
}
}
}
我得到无法将类型“()”的返回表达式转换为返回类型“String”的错误。
知道我做错了什么吗?
在for循环后直接添加completionhandler(详细信息,无)
for line in lines {
let entries = line.split(separator: ";").map { String($0) }
if entries.count == 4 {
let newMachine = MachineDetails(machineNumber:entries[0],
machineName:entries[1],
machineXML:entries[2],
machineWiFi:entries[3])
details.append(newMachine)
} else {
print("Malformed line \(line)")
}
}
completionHandler(details, nil)
返回闭包时,返回的不是getMachineName
函数,而是闭包本身。注意,闭包被定义为具有类型([MachineDetails]?,Error?)->void
,意思是一旦调用它,就不会在闭包中返回。通常,当您在函数中使用闭包,并且希望从该函数中获取值时,该函数也有闭包。您可以重新格式化该函数,如下所示:
func getMachineName(machineNumber: String, completion: @escaping (String) -> Void) {
getMachineDetails { (machineDetails, error) in
if let machineDetails = machineDetails {
let index = machineDetails.firstIndex { $0.machineNumber == machineNumber }
completion(machineDetails[index].machineName)
}
}
}