Boolean with swift - ios

This is really confusing. Does anyone have any ideas?
let viewHasMovedToRight == false //initially I want this to be false
then
func moveViewToRight(sender: UIButton!) {
if viewHasMovedToRight == false {
viewHasMovedToRight == true;
UIView.animateWithDuration(
0.75,
animations: {},
completion: { (value: Bool) in
println(" moved")
}
)
}
else {
viewHasMovedToRight == false;
UIView.animateWithDuration(
0.75,
animations:{},
completion:{ (value: Bool) in
println("not moved")
}
)
}
// println("move view")
}
Only the first if is called.
I cannot re-assign the value back to true...
Something that was so easy on Obj-C now with swift is so frustrating...

You have two problems.
One, you are using == (which tests for equality) where you should be using = (which assigns a value). Two, you are declaring a constant and then trying to assign a new value to it later. You need to declare a variable.
var viewHasMovedToRight = false
...
viewHasMovedToRight = true
Also, most people would find this if condition more understandable:
if !viewHasMovedToRight {
And it would be even simpler if you were to reverse the order of your if clauses:
if viewHasMovedToRight {
viewHasMovedToRight = false
...
} else {
viewHasMovedToRight = true
...
}

let viewHasMovedToRight = false not let viewHasMovedToRight == false
EDIT: It looks like you use == instead of = everywhere you are setting the boolean.

#George,
you should use set operator
let viewHasMovedToRight = false
not comparison operator
let viewHasMovedToRight == false

Newbie here.
I used to do that mistake all the time, using = both for assign and to compare.
Use = to assign and == to compare

Related

How to fix conditional binding have optional type not 'Bool'?

how can I solve this problem?
Ive been getting the same error in 10 different places, I have been running tests on it and can't seem to figure this
thanks in advance for any help that you guys provide it really means a lot to me
Initializer for conditional binding must have Optional type, not 'Bool'
extension HomeController: FiltersViewControllerDelegate{
func query(withCategory jewelry: Bool, shoe: Bool, hat: Bool, apearel: Bool, gear: Bool) -> Query {
if jewelry == false && shoe == false && hat == false && apearel == false && gear == false {
stackViewHeightConstraint.constant = 0
activeFiltersStackView.isHidden = true
} else {
stackViewHeightConstraint.constant = 44
activeFiltersStackView.isHidden = false
}
var filtered = baseQuery
// Sort and Filter data
if let jewelry = jewelry, !jewelry.isEmpty { //Error
filtered = filtered.whereField("category", isEqualTo: jewelry)
}
//......more Filters....\\
if let gear = gear, !gear.isEmpty { //Error
filtered = filtered.whereField("category", isEqualTo: gear)
}
return filtered
}
func controller(_ controller: FilterViewController,
didSelectCategory jewelry: Bool,
shoe: Bool,
hat: Bool,
apearel: Bool,
gear: Bool) {
if jewelry == false && shoe == false && hat == false && apearel == false && gear == false {
stackViewHeightConstraint.constant = 0
activeFiltersStackView.isHidden = true
} else {
stackViewHeightConstraint.constant = 44
activeFiltersStackView.isHidden = false
}
let filtered = query(withCategory: jewelry, shoe: shoe, hat: hat, apearel: apearel, gear: gear)
if let jewelry = jewelry, ! jewelry.isEmpty { //Error
jewelryFilterLbl.text = "Jewelry"
jewelryFilterLbl.isHidden = false
} else {
jewelryFilterLbl.isHidden = true
}
//......more Filters....\\
if let gear = gear, !gear.isEmpty { //Error
gearFilterLbl.text = "gear"
gearFilterLbl.isHidden = false
} else {
gearFilterLbl.isHidden = true
}
query = filtered
}
}
Remove .isEmpty check it's not a property of a Bool
if jewelry { //Error
filtered = filtered.whereField("category", isEqualTo: jewelry)
}
//......more Filters....\\
if gear { //Error
filtered = filtered.whereField("category", isEqualTo: gear)
}
You're using if let binding on variables that are not optionals.
For example, your jewel variable is a Bool, not a Bool?. Using optional binding doesn’t make any sense.
if let jewelry = jewelry, ! jewelry.isEmpty { // Jewelry isn't an Optional!!!
jewelryFilterLbl.text = "Jewelry"
jewelryFilterLbl.isHidden = false
} else {
jewelryFilterLbl.isHidden = true
}
Plus, as other users have stated, Bool variables don't have .isEmpty method. Revise your logic and your code, it doesn't work at all.

Get the content of an array of labels in Swift

I'm trying to check the content of an array of labels but it not works.
To explain the program: I have 4 arrays of 4 UIlabels each one and every label contains a number in String. This function returns true if one label contains the number 16. I tried to use the function "contains" but it doesn't work because "16" it's a string and not a label.
Thanks
Example of declaration of array of labels:
Fila1 = [UILabel]()
Function Win:
func win() -> Bool {
for i in 0..<Fila1.count {
if(Fila1[i].text == "16") {
return true
} else if(Fila2[i].text == "16") {
return true
} else if(Fila3[i].text == "16") {
return true
} else if(Fila4[i].text == "16") {
return true
} else {
return false
}
}
return false
}
The issue is that you shouldn't have that else statement return false.
It should be:
if(Fila1[i].text == "16") {
return true
} else if(Fila2[i].text == "16") {
return true
} else if(Fila3[i].text == "16") {
return true
} else if(Fila4[i].text == "16") {
return true
} // end if here
You're exiting out of the loop too early. If the first element isn't what you are looking for you aren't checking the rest.
Your code is fine, you just need to remove the else condition that contains return false and the code should work as expected.

I am not sure why my else if is not being called in my IBAction

I have created an IBAction that handles 2 buttons, first one's title is "True" and the second one's title is "False", when tapped they should display a label however the else if never gets called.
#IBAction func trueOrFalse(sender: UIButton) {
if sender.currentTitle == "True" {
answerR.hidden = false
answerW.hidden = true
} else if sender.currentTitle == "False" {
print("hi")
answerW.hidden = false
answerR.hidden = true
}
}
answerW and answerR are the labels.
I am not sure why, I have tried a couple of things like using taps but I can not seem to figure it out.
Sounds like one of your buttons isn't registering the IBAction - double check and make sure each are connected via Touch Up Inside. If they are connected w/ a different method it may not register as you expect!
You should use button tags. It is very simple like below:
Firstly, you should set each button tag like below:
Buton1 Tag = 0
Buton2 Tag = 1
Then use below code:
#IBAction func trueOrFalse(sender: UIButton) {
if sender.tag == 0 {
answerR.hidden = false
answerW.hidden = true
}else
{
print("hi")
answerW.hidden = false
answerR.hidden = true
}
}
you need to eliminate optional that comes with string
#IBAction func trueOrFalse(sender: UIButton) {
if (sender.currentTitle!)! == "True" {
answerR.hidden = false
answerW.hidden = true
} else if (sender.currentTitle!)! == "False" {
print("hi")
answerW.hidden = false
answerR.hidden = true
}
}

swift - sort an array of objects by their optional boolean property without force unwrapping

I can sort this array of store objects by their 'flagship' boolean property, but how can I safely unwrap the 'flagship' property first?
let flagshipStores = self.stores.sort {
$0.flagship! && !$1.flagship!
}
let flagshipStores = self.stores.sort {
guard let flagship0 = $0.flagship, let flagship1 = $1.flagship else { return false }
return flagship0 && !flagship1
}
One more approach: turn the Bool? into an Int, then compare the Ints. You get to specify how a nil value compares to non-nil values.
For instance, this sorts nil values before both false and true:
stores.sort { Int($0.flagship ?? -1) < Int($1.flagship ?? -1) }
This sorts nil values after both false and true:
stores.sort { Int($0.flagship ?? 2) < Int($1.flagship ?? 2) }
You can use the same pattern to make nil compare the same as true or the same as false. It's up to you.
Here's another approach.
You can use flatMap which will remove nil objects and unwrap those that are present. Then, the force unwrap will be safe to sort:
let flagshipStores = stores.flatMap({ return $0.flagship ? $0 : nil }).sort {
$0.flagship! && !$1.flagship!
}
This will remove stores with a nil flagship from the array.
How about:
$0.flagship == true && $1.flagship != true
The left side will succeed if the value is not nil and is true, the right side will succeed if the value is either nil or false.
As mr.Fixit pointed out on a comment, the accepted answer doesn't fully work because it doesn't take care of nils. Here is the correct answer with an extra string sample.
SWIFT 4
for a boolean sorting
let flagshipStores = self.stores.sorted(by: {
guard let flagship0 = $0.flagship, let flagship1 = $1.flagship else {
if $0.flagship == nil && $1.flagship == nil || $0.flagship != nil && $1.flagship == nil{
return true
}
else {
return false
}
}
return ($0.flagship == $1.flagship || $0.flagship == true && $1.flagship == false ? true : false)
})
for strings comparison sorting
let stores = self.stores.sorted(by: {
guard let store0 = $0.store, let store1 = $1.store else {
if $0.store == nil && $1.store == nil || $0.store != nil && $1.store == nil{
return true
}
else {
return false
}
}
return ( ($0.store)?.localizedStandardCompare($1.store!) == ComparisonResult.orderedAscending )
})
To filter nil values just use compactMap before sort
let flagshipStores = self.stores.compactMap { return $0.flagship }.sorted {
$0 && !$1
}
You could use this function to compare the Optional values without the need to unwrap.
func sortOptionalValues<T: Comparable>(lhs: T?, rhs: T?) -> Bool? {
switch (lhs != nil, rhs != nil) {
case (false, false):
return nil
case (true, false):
return true
case (false, true):
return false
case (true, true):
guard let lhs = lhs, let rhs = rhs else { return nil }
return lhs < rhs
}
}

Swift: Run code when object is within an area

I'm making a true or false game where the we have to determine if the logical expression is true or false. It's a one click game. If we click, the current true condition changes to false and vice versa. A series of logical expression will pop down the screen and when it reaches the zone, the current condition must equal to the logical expression to get a score. To verify the truth value, it checks the image of the truth value. I tried one case, where it is 'true and true' and the current condition is true, which is true. However, when it passes through the zone, the score did not increase. Where did I go wrong?
#IBAction func button_clicked(sender: UIButton) {
if (truth_click == true) {
truth_click = false
self.truth_button.image = UIImage(named: "false_button")
}
else if (truth_click == false) {
truth_click = true
self.truth_button.image = UIImage(named: "true_button")
}
}
func check_truth() {
if (truth_click == true) {
//when it reaches the zone
if (left_truth.center.y > 330 ) {
//if true and true
if ((left_truth.image == UIImage(named: "true")) && (symbol.image == UIImage(named: "and")) && (right_truth.image == UIImage(named: "true"))) {
self.score += 1
}
//if true and false
//if false and true
//if false and false
self.score_label.text = String(self.score)
}
}
if (truth_click == false) {
//when it reaches the zone
if (left_truth.center.y > 330 ) {
//if true and false
if ((left_truth.image == UIImage(named: "true")) && (symbol.image == UIImage(named: "and")) && (right_truth.image == UIImage(named: "false"))) {
self.score += 1
}
//if true and true
//if false and true
//if false and false
self.score_label.text = String(self.score)
}
}
}
Part of your problem is testing *_truth.image against new instances of UIImage(named:...). UIImage is an object. Instantiating a new UIImage creates a new object. Two objects with the same content are not equal ...without extra work.

Resources