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

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)")
}

Related

Swift Fatal error: Index out of range (out of bounds index)

Hello I am trying to learn swift. I have a little experience with javascript so i tried modeling this loop in the same manner i usually do. The function actually outputs what its supposed to but I keep getting an error message and I am unsure of what I am doing wrong. Here is my code:
import UIKit
let dir: [String] = ["north", "east", "south", "west"]
var num = dir.count
func move(){
for i in 0 ... num{
var holder = dir[i]
switch holder{
case "north":
print("you've moved north")
case "east":
print("you've moved east")
case "south":
print("you've moved south")
case "west":
print("you've moved west")
default:
print("where you going?")
}
if i == 3{
print("round the world")
}
}
}
move()
i get this error on the last line "move()"
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION
(code=EXC_I386_INVOP, subcode=0x0).
this is what outputs to the console:
you've moved north
you've moved east
you've moved south
you've moved west
round the world
Fatal error: Index out of range: file
/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.2.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift,
line 444
In your code trying to access 4th index due to you have used ... in loop control syntax. And 4th index not in array.
Here is some details about for swift loop.
for index in 0...4 {
...
}
The above snippet says, iterate over the range starting at 0 and inclusive of 4 i.e from 0–4
If you do not want 4 included, you use this called the half-open range operator (..<).
for index in 0..<4 {
...
}
This would loop from 0 to 3 and stop execution.
In swift, there're more efficient ways to loop...but to better understand what you implemented...
I've updated your code...it will run properly.
let dir: [String] = ["north", "east", "south", "west"]
var num = dir.count
func move(){
for i in 0..<num{
var holder = dir[i]
switch holder{
case "north":
print("you've moved north")
case "east":
print("you've moved east")
case "south":
print("you've moved south")
case "west":
print("you've moved west")
default:
print("where you going?")
}
if i == 3{
print("round the world")
}
}
}
move()
Output :-
you've moved north
you've moved east
you've moved south
you've moved west
round the world
Happy Coding in Swift :-)
import UIKit
class ViewController: UIViewController {
let dir: [String] = ["north", "east", "south", "west"]
override func viewDidLoad() {
super.viewDidLoad()
move()
// Do any additional setup after loading the view.
}
func move(){
for (index, element) in dir.enumerated() {
// print("Item \(index): \(element)")
switch element{
case "north":
print("you've moved north")
case "east":
print("you've moved east")
case "south":
print("you've moved south")
case "west":
print("you've moved west")
default:
print("where you going?")
}
if index == 3{
print("round the world")
}
}
}
}
So, here you are first taking count of the num which is here 4.

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"
}
}

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

Switch statement inside if statement

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

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