Reputation: 1969
I have a problem in swift 2.0
here is the current block of code that I write:
let URL = NSURL(string:"www.google.com")
and then I get the following warning:"initialization of immutable value URL was never used, consider replacing with assignment to '_' or removing it.
What should i do when I want to declare a let.
I get a similar warning when writing
What can I do in swift 2.0 to declare a Let or a var?
Upvotes: 0
Views: 587
Reputation: 45
You should change var
to let
to resolve this warning.
To save memory, Compiler recommend user to use let
instead of var
when you only need to get value from a variable but not set
Upvotes: 0
Reputation: 6282
initialization of immutable value URL was never used
Means that you didn't use the variable anywhere, so its throwing a warning. But looking at the screenshot, you have declared URL
as a var
and used it in data
which is another var.
So there should be two warnings now. URL
is declared as a var
but never mutated and data
variable was never used.
To satisfy, use let URL ...
since you are not mutating it. and do away with data
as this is a async block/closure and you can access data
from the completion block.
Note:
You should use let
when you are not modifying it later and you should use var
when you want to modify the object. Consider array :
let immutableArray:[String] = ["foo", "bar"]
var mutableArray:[String] = ["hello"]
mutableArray.append("World") // Is valid since its a var
immutableArray.append("abc") // Not valid, infact auto complete does not even show append methods
Upvotes: 4
Reputation: 1145
this may work fine.
let URL = NSURL(string:"www.google.com")
NSURLSession.sharedSession().downloadTaskWithURL(URL!) { (url: NSURL?, response: NSURLResponse?, error: NSError?) -> Void in
if error == nil && url != nil {
let data = NSData(contentsOfURL: url!)
print(data)
}
}
Upvotes: 0
Reputation: 5477
Whenever you are declaring a let
and not using that constant complier will show a warning. There is nothing to worry about. If you are not using let
constant replace it with _
. It is for optimization. If you are not using remove that let. Or to silence warning use a simple print(YOUR Constant)
For your case user
let url = URL = NSURL(string:"www.google.com")
Than
let data = NSURLSession.sharedSession().downloadTaskWithURL(URL!) {
{ (data, response, error) in {
if(error != nil) {
print(data) // This data is different from let data constant
}
print(data) // This will silence warning. Also make sure it is not nil
Upvotes: 0