Swift Basics - filtering

Filtering with the where statement:
for number in 1...50 where number % 3 == 0
{
}
//get numbers from 1 to 50 that can be divided by 3 without remainder

Filtering using for case:
var pupilsWhoWon = [("Mary", 10), ("John", 50), ("Mary", 80)]
for case let ("Mary", score) in pupilsWhoWon { print(score)}

Filter out nil values:
let myNum: [Int?] = [1, 2, nil, 3, nil]
for case let .some(num) in myNum
{
  print(num)
}
//each optional value is an enumeration with either case none or some. If there is a value, it would have case some.
You can filter out the numbers that have a value are are more than 3:
for case let num? in myNum where num > 3 {}

You can use if case statements for enumerations:

enum Book{
case Title(String)
case Edition(Int)
case Author(String)
}

var thisBook = Book.Edition(2)
if case let .Edition(num) = thisBook
{print("This book's edition is \(num)")}
OR
if case let .Edition(num) = thisBook, num == 2
{}
//Checks to see if thisBook has a value of edition and the associated number for the edition is 2

Comments

Popular posts from this blog

Setting up a playground

Go to another page