variable was written, but never read? - ios

Im getting the following warning variable 'isTaken' was written to, but never read on the following code :
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
var isTaken: Bool = false
if textField == usernameTxt { var query = PFQuery(className: "_User")
query = PFQuery(className: "_User")
query.whereKey("username", equalTo: usernameTxt.text!)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) in
if error == nil {
if (objects!.count > 0){
isTaken = true
}
} else {
print("Username is available. ")
}
} else {
print("error")
}
}
}
return true
}
why am I getting the warning and how do I do away with it?

As error says variable 'isTaken' was written to, but never read means you are creating isTaken instance and assigning a value to it but it never used.

Just eliminate the statements:
var isTaken: Bool = false
isTaken = true
Since the value is never used, defining and assigning to it accomplishes nothing.

Basically it's saying that isTaken is assigned a value, but it doesn't actually do anything in your code. You are never using it or checking it's value, so it's simply an warning saying that the variable is unnecessary.
If you actually are using isTaken and the compiler doesn't realize for some reason, you could probably just add another line right after
isTaken = true;
that just says
isTaken;
Or make isTaken global if you're using somewhere else in the code.

Its a compiler warning to point out a dead code. You probably have copy pasted some code and removed some unwanted code. In doing so, usage of local variable isTaken is gone. So, its only being assigned a value and never used for materializing any benefits. You can either simply remove the code around isTaken or double check and put back the functionality around it :).

It's warning you about a var that you set a value, but don't operate over it after.
Is very important keep your code clean and safe, so the xcode just gives you a little help with it.
isTaken = true;
Thats the point you set a value to isTaken variable.
Try to review your code and think about the use of this variable.

I recommend that you do not do this, but the build setting is GCC_WARN_UNUSED_VARIABLE. You can disable it, but again, do not.
I am adding the setting name here because I was searching to find it so that I could check its value in my project, but no question or answer mentioned its name.

Related

segmentation fault 11 in swift2

I have no idea why I get this error.
The problem code is here
for i in 0..<itemDataJson?.count {
imageUrls.append(appDelegate.itemDataJson![i]["image_url"].string!)
}
When I print(itemDataJson?.count) it prints Optional(1).
What am I doing wrong?
Thank you.
It's printing Optional(1) because the variable itemDataJson is nullable, so the count would therefore have to be nullable, because we don't know if itemDataJson actually has a value.
The main problem that I see in your code is that you are force-unwrapping variables. Force-unwrapping a variable is a code smell (usually, although I do it myself from time to time, but you need to be careful).
When you force unwrap a variable, you need to ask yourself the question, "Do I want the app to crash here if this variable is nil?". If the answer is yes, then using a force unwrap is acceptable, otherwise, you should create a non-nullable variable or if that is not possible, you should use the guard statement in swift.
This could be used like this:
guard let itemDataJson = itemDataJson else {
// itemDataJson was null do something
return
}
You can use the if let construct as well, but be careful of the pyramid of doom if you don't use the if let construct correctly. See here for using it correctly, or use a guard statement.
I would recommend checking out the documentation on optionals if you have not done so already.
I would change the code to this version:
if (itemDataJson != nil) {
for i in 0..<itemDataJson!.count {
imageUrls.append(appDelegate.itemDataJson![i]["image_url"].string!)
}
}
You should check all optionals before you try to access the underlying value. Best course of action would be to use if let statements.
if let itemDataJSON = itemDataJSON {
for i in 0..<itemDataJSON.count {
if let items = appDelegate.itemDataJSON {
if let imageURL = items[i]["imageURL"].string {
imageUrls.append(imageURL)
}
}
}
}
Other than that, it's a bad practice to store data in AppDelegate. You should create your own data layer that is not dependent of AppDelegate to make data handling more efficient and easier.
instead of checking for nil you should try this.
if let item = itemDataJson {
for i in 0..<item.count {
imageUrls.append(appDelegate.itemDataJson![i]["image_url"].string!)
}
}

Access Optional property in multiple function for calculations - Swift

I have a NSObject Subclass. Say CityWalks
class CityWalks{
var totalCount:Int?
}
How do I use this property further? Should I check the nil coalescing every time this value is accessed.
example:
let aObject =
say in one fucntion (function1()) , I need to access this value, then it would like (aObject!.totalCount ?? 0)
func function1(){
...Some Access code for the object....
(aObject!.totalCount ?? 0)
}
Similarly in every other function(function2()) , I will have to write the same code.
func function2(){
...Some Access code for the object....
(aObject!.totalCount ?? 0)
}
So, what could be a better approach for such field, considering this property might receive a value from server or might not.
If you have a default value for this property just assign this value as default value.
class YourClass {
var totalCount = 0
}
I'd recommend you avoid using an optional value if it's possible. Because optional values its a first place when you can get an error.
As stated in the comments and the other answer using an optional is not really optimal in your case. It seems like you might as well use a default value of 0.
However, to clarify, you have to check the value when unwrapping the optional.
Sometimes it's possible to pass an optional to UIElement etc and then you don't really need to do anything with them
There are pretty ways of checking for nil in optional values built into swift so you can build pretty neat code even though you work with optional.
Look in to guard let and if let if you want to know more about unwrapping values safely.
if let
if let totalWalks = aObject?.totalCount {
//operate on totalWalks
}
guard
guard let totalWalks = aObject?.totalCount else { return }
//operate on totalWalks
There are also cases where you will want to call a function on an optional value and in this case you can do so with ?
aObject?.doSomething()
Any return values this function might have will now be wrapped in an optional and you might have to unwrap them as well with an if let or guard
When working with optionals you should try to avoid forcing the unwrap with ! as even though you at the moment know that the value is not null that might after a change in the code not be true anymore.

Swift - Variable doesn't retain value

I am using AWS to host images for my iOS app. Right now I am trying to list all the objects in an S3 bucket.
Here is my code:
var description = ""
AWSS3.registerS3WithConfiguration(serviceConfig2, forKey: "s3")
AWSS3.S3ForKey("s3").listObjects(objectList).continueWithBlock { (task: AWSTask!) -> AnyObject! in
if task.error != nil {
println(task.error)
}
if task.result != nil {
description = task.result!.description
println(description)
}
return nil
}
println(description == "")
The output is true followed by the correct contents of task.result!.description. In other words, the println outside of the continueWithBlock is printing first and description has not been updated at that time.
How am I supposed to do things with description outside of the continueWithBlock?
You can assign a value that you need to another variable inside the scope of your class or function, then you can call didSet on the variable and carry out another function if you need to, like this:
var someVariableInScopeOfWhereItsNeeded = "abc" {
didSet {
self.maybeSomeOtherFunctionNow
}
}
You asked:
How am I supposed to do things with description outside of the
continueWithBlock
Short answer: You're not.
The whole point of an async method is that it continues immediately, before the time-consuming task has even begun processing. You put the code that depends on the results inside your block. See my answer on this thread for a detailed explanation, including an example project:
Why does Microsoft Azure (or Swift in general) fail to update a variable to return after a table query?
(Don't be fooled by the fact that it mentions MS Azure. It actually has nothing to do with Azure.)
#thefredelement 's solution of using a didSet method on the variable that gets set would work too.

Swift Optionals - Unexpectedly found nil when unwrapping an optional value

I'm new to Swift and have been trying to wrap (ha) my head around optional values. As far as I can see - although I'm probably wrong - variables can be optional and therefore contain a nil value and these have to be accounted for in code.
Whenever I hit the 'save' button in my application I get the error: 'fatal error: unexpectedly found nil while unwrapping an Optional value'.
#IBAction func saveTapped(sender: AnyObject) {
//code to save fillup to Parse backend
// if variable is not nil
if let username = PFUser.currentUser()?.username {
// set username equal to current user
self.object.username = username
}else{
println("PFUser.currentUser()?.username contained a nil value.")
}
// if variable is not nil
if let amount = self.amountTextField.text {
//set amount equal to value in amountTextField
self.object.amount = self.amountTextField.text
}else{
println("self.amountTextField.text contained a nil value.")
}
// if variable is not nil
if let cost = self.costTextField.text {
// set cost equal to the value in costTextField
self.object.cost = self.costTextField.text
}else{
println("self.costTextField.text contained a nil value.")
}
// set date equal to the current date
self.object.date = self.date
//save the object
self.object.saveEventually { (success, error) -> Void in
if error == nil {
println("Object saved!")
}else{
println(error?.userInfo)
}
}
// unwind back to root view controller
self.navigationController?.popToRootViewControllerAnimated(true)
}
Not sure if the error is because of something in this block of code or somewhere else - can provide the main class code if needed.
Any help anyone can provided would be really appreciated as this has been bugging me for a while now.
From your code and the comments it sounds like your issue definitely lies with self.object
Your code never uses an if let statement to check to ensure self.object is not nil
Using println(username) works because your username is not nil. But when you try to call self.object.username, it's the self.object that is causing the crash.
You may have a property in your implementation like var object:CustomPFObject! which means, the first time you access this variable it's expected to not be nil. You'll probably want to check the code where you are setting self.object for the first time, and to make sure that it's being set before you've tried to access it.
If you're not able to manage when self.object is set, and when it's accessed, then change your declaration to var object:CustomPFObject? Now it's an optional, and as you write your code you'll be forced to make decisions as you go along.
For example:
var object:CustomPFObject?
let text = self.object.username //won't compile
let text = self.object!.username //mighty crash
let text = self.object?.username //you're safe, 'text' just ends up nil
I hope this helps you solve your issue.

Logical AND with Swift Optional in IF statement

I have two properties. One of them is optional. these are defined below:
var advertiseCompleteBlock: (() -> ())!
var isAdvertiser: Bool = false;
Now, if I try to use this in my code like below, the compiler throws an error while building and fails with error code 254.
if (self.isAdvertiser && self.advertiseCompleteBlock) {
self.advertiseCompleteBlock();
}
But if I change it like below, it works fine:
if (self.isAdvertiser && self.advertiseCompleteBlock) {
if (self.advertiseCompleteBlock) {
self.advertiseCompleteBlock();
}
}
Can anyone explain how are these two blocks of code different and what am I doing wrong here?
If advertiseCompleteBlock is really optional it should probably be declared with a ? instead of ! which says that it will always exist.
I put your original code in a test file as a simple func and removed the references to self and it compiled fine. I don't know what the error 254 would be.
Is this code really what you want?
var advertiseCompleteBlock: (() -> ())? --> really optional
var isAdvertiser: Bool = false;
if (isAdvertiser && advertiseCompleteBlock) {
advertiseCompleteBlock!(); --> but now guaranteed
}
Your block var is optional and is not initialized. So while unwrapping it will definitely be nil which compiler does not expect. That's the reason you get the compile errors.
In the second case you are checking if the var is nil or not and then calling the block, so the compiler is happy in this case.

Resources