Switch statement inside if statement - ios

I am trying to have a switch statement inside of an if statement checking integers
if variable <= 3 {
// code
switch variable {
case 0:
println("0 case")
case 1:
println("1 case")
case 2:
println("2 case")
case 3:
println("3 case")
default:
println("error")
}
}
But I am getting an error for each case
Binary operator '~=' cannot be applied to operands of type 'Int' and 'Int?'
I do not understand why this wouldn't work.

3 is an Int but variable is an Int? (an optional Int). You have to unwrap it.
For example, you can check if it's nil in the if statement. If it's not, then it's safe to force-unwrap (with !) inside the scope of that conditional:
One of many possible approaches:
if variable <= 3 && variable != nil {
// code
switch variable! {
case 0:
println("0 case")
case 1:
println("1 case")
case 2:
println("2 case")
case 3:
println("3 case")
default:
println("error")
}
}

var variable : Int? will not work
var variable = 2
//var variable : Int? // will not work
if variable <= 3 {
// code
switch variable {
case 0:
println("0 case")
case 1:
println("1 case")
case 2:
println("2 case")
case 3:
println("3 case")
default:
println("error")
}
}

If your variable is an Optional, be aware that if it's nil then in your initial if statement the expression nil <= 3 returns true.
So, the most comprehensive form your can choose (IMHO) is:
var variable : Int? = ...
switch variable {
case .Some(0):
print("1 case")
case .Some(1):
print("2 case")
case .Some(3):
print("3 case")
case .Some(let x):
print("We got \(x)")
case .None:
print("variable is nil")
}
Note:
print is Swift 2.0. Use println in Swift 1.2

Related

Switch case warning in swift

I have switch condition on Int32 attribute of core-data entity as
switch location.userLocationLike?.likeStatusId {
case 1 as Int32:
view.lblLike.text = "LIKED"
case 2 as Int32:
view.lblLike.text = "OKAY"
case 3 as Int32:
view.lblLike.text = "DISLIKE"
default:
view.lblLike.text = "LIKE"
}
If I don't type cast value as Int32 than it shows error, And if I convert it to Int32 than warning. Can anyone please explain me what is the best way to write Switch-case.
The error is misleading, you cannot switch on an optional with non-optional cases, optional bind (or even forced unwrap) userLocationLike, according to the warnings the as Int32 casts are meaningless.
if let likeStatus = location.userLocationLike {
switch likeStatus.likeStatusId {
case 1: view.lblLike.text = "LIKED"
case 2: view.lblLike.text = "OKAY"
case 3 view.lblLike.text = "DISLIKE"
default: view.lblLike.text = "LIKE"
}
}

How to make switch statement with optionals?

I'm working with text fields and json data. I want to test if the json data is != nil, if it is, then I fill it's field with that info, if it's == nil then I put a placeholder in its field instead. Like this:
if memberInfo?.createDate != nil {
self.activeSinceTextField.text = stringToDateToString((memberInfo?.createDate)!)
} else {
placeHolder("Enter Here".localized())
self.activeSinceTextField.attributedPlaceholder = placeHolderText
}
if memberInfo?.birthDate != nil
{self.birthdayTextField.text = stringToDateToString((memberInfo?.birthDate)!)
} else
{ placeHolder("Enter Here".localized())
self.birthdayTextField.attributedPlaceholder = placeHolderText
}
I have a lot of fields and I'm thinking a switch statement would make this a lot cleaner. I'm just not sure how to make one for this type of situation.
Version 1
This is how you define the 4 outcomes with a switch
switch (memberInfo?.createDate, memberInfo?.birthDate) {
case (.Some, .Some): break
case (.Some, nil): break
case (nil, .Some): break
case (nil, nil): break
}
Now just replace the break(s) with the code you want to execute for each scenario.
Version 2
Here you have createDate and/or birthDate unwrapped when available
switch (memberInfo?.createDate, memberInfo?.birthDate) {
case (let .Some(createDate), let .Some(birthDate)):
print(createDate, birthDate)
case (let .Some(createDate), .None):
print(createDate)
case (.None, let .Some(birthDate)):
print(birthDate)
case (.None, .None):
print("Both are nils")
}
Legend
.Some: means here there is something
.None: means this is nil
_: means is a jolly, it means I don't care what there is here

Why fallthrough concept of switch case not allowed in swift? [duplicate]

This question already has answers here:
swift case falling through
(5 answers)
Closed 6 years ago.
var index = 30
switch index {
case 10 :
println( "Value of index is 10")
case 20 :
case 30 :
println( "Value of index is either 20 or 30")
case 40 :
println( "Value of index is 40")
default :
println( "default case")
}
Fallthrough is allowed in Swift, but you do have to state it explicitly:
switch index {
case 10:
println( "Value of index is 10")
case 20:
fallthrough
case 30:
println( "Value of index is either 20 or 30")
...
For your situation though, it's probably better to just group your cases:
switch index {
case 10:
println( "Value of index is 10")
case 20, 30:
println( "Value of index is either 20 or 30")
...
Or you can write it this way (Swift 2.2 syntax):
switch index {
case 10:
print("Value is: \(index)")
case 20, 30:
print("Value is: \(index)")
default:
print("Default value is: \(index)")
}

Initialized enum returns wrong hashValue

This is Swift 1.2 and I'm using Xcode 6.4. The following enum has a failable initializer.
enum EstimateItemStatus: Int, Printable {
case Pending = 1
case OnHold = 2
case Done = 3
var description: String {
switch self {
case .Pending: return "Pending"
case .OnHold: return "On Hold"
case .Done: return "Done"
}
}
init?(id : Int) {
switch id {
case 1:
self = .Pending
case 2:
self = .OnHold
case 3:
self = .Done
default:
return nil
}
}
}
If I pass an ID and initialize an instance, the enum value I get is correct. However the hashValue is wrong. For example,
let status = EstimateItemStatus(id: 2)!
println("\(status.hashValue) - \(status)")
The output I get is 1 - On Hold.
But it should be 2 - On Hold.
What am I doing wrong here? Is this a compiler bug or am I missing something?
Demo playground
Maybe you're mixing up hashValue vs. rawValue.
The hash value is not enforced to be equal to the raw value

How to compare switch statement control expression with its patterns in swift?

I have a tried this and it does not work:
let value1 = 12
let sumOfOtherValues = 10 + 1 + 24
switch value1 {
case let (value1,sumOfOtherValues) where (value1 > sumOfOtherValues):
break;
case value1..>sumOfOtherValues:
break;
default:
breaK;
}
I would really like to make this in a switch statement and not in an if statement.
is this what you need? (I don't understand your need for value1..>sumOfOtherValues
let value1 = 12
let sumOfOtherValues = 10 + 1 + 24
switch value1 {
case _ where sumOfOtherValues > value1:
println("case 1")
//break //it's not mandatory.
fallthrough //Without this code, this will stop here if the switch match this case. If you want that your switch continue to search, add 'fallthrough' at the end of each case
case _ where value1 > sumOfOtherValues:
println("case 2")
break
default:
break
}

Resources