Swift-使用未解决的标识符 [英] Swift - Use of unresolved identifier
问题描述
我在同一函数中创建所有变量.但是在函数的最后,即使它是在同一函数中创建的,我也无法达到该常数.
I create all the variables within the same function. But at the end of the function I can't reach the constant even though it was created in the same function.
当我在结尾处写"self.resultLabel.text = weather"时,Xcode向我显示错误使用了未解析的标识符"weather"
When I write "self.resultLabel.text = weather" at the end, Xcode shows me an error use of unresolved identifier 'weather'
我知道该如何解决.我需要在task方法启动后立即启动天气"并将其设置为",然后我应该在函数中更改其值,但是即使我不这样做并且我在if闭包中创建它,也不应该我可以在同一功能范围内到达它吗?
I know how to fix it. I need to initiate 'weather' just after the task method starts and set it to "" and then I should change its value in the function but even if I don't do it and I create it in the if closures, shouldn't I be able to reach it while within the same function?
我不明白为什么它让我一直犯这个错误.
I don't understand why it keeps me giving this error.
func findWeather() {
var errorStatus = false
city = (cityField.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()))!
let url = NSURL(string: "http://www.weather-forecast.com/locations/" + city.stringByReplacingOccurrencesOfString(" ", withString: "-") + "/forecasts/latest")!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
if let content = data {
let urlContent = NSString(data: content, encoding: NSUTF8StringEncoding) as NSString!
let weatherContent = urlContent.componentsSeparatedByString("<span class=\"phrase\">")
if weatherContent.count > 1 {
let weather = weatherContent[1].componentsSeparatedByString("</span>")[0].stringByReplacingOccurrencesOfString("°", withString: "˚")
} else {
var weather = ""
errorStatus = true
}
} else {
var weather = ""
errorStatus = true
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if errorStatus == true {
self.showError()
} else {
self.resultLabel.text = weather // I get error: use of unresolved identifier 'weather'
}
})
}
task?.resume()
推荐答案
您正在定义太多新变量weather
,这些变量仅在它们所在的花括号之间局部可见.
You're defining too many new variables weather
which are all visible only locally between the curly braces they are in.
定义weather
的最佳位置是task
闭包的开头,并且必须删除该变量随后出现的所有var
或let
声明.
The best place to define weather
is at the beginning of the task
closure and all var
or let
declarations of the subsequent occurrences of the variable have to be deleted.
这是关键部分:
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
var weather = ""
if let content = data {
let urlContent = NSString(data: content, encoding: NSUTF8StringEncoding) as NSString!
let weatherContent = urlContent.componentsSeparatedByString("<span class=\"phrase\">")
if weatherContent.count > 1 {
weather = weatherContent[1].componentsSeparatedByString("</span>")[0].stringByReplacingOccurrencesOfString("°", withString: "˚")
} else {
errorStatus = true
}
} else {
errorStatus = true
}
...
这篇关于Swift-使用未解决的标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!