Using Switch statement in Swift?

What is Switch statement?

According to Swift document, a switch statement is:

A switch statement considers a value and compares it against several possible matching patterns. It then executes an appropriate block of code, based on the first pattern that matches successfully. A switch statement provides an alternative to the if statement for responding to multiple potential states.

Basiclly speaking, in a switch statement, it will try all possible values for a variable. Also, a switch statement must have a default value.

All the following code are based on Swift 3.0.

A Simple Example

Output is Ten for the example below.

Swift program that uses switch

1
2
3
4
5
6
7
8
9
10
11
12
let id = 10

switch id {
case 9:
print("Nine")
case 10:
print("Ten")
case 11:
print("Eleven")
default:
break
}

Multiple Case Values Example

Output is Medium for the example below.

Swift program that uses multiple case values

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let size = 3

// Switch on the size Int.
switch size {
case 0, 1:
// Two values match Small.
print("Small")
case 2, 3:
// Two values match Medium.
print("Medium")
case 4, 5:
// Two values match Large.
print("Large")
default:
break
}

Ranges Example

Output is Upper half for the example below.

Swift program that uses ranges in cases

1
2
3
4
5
6
7
8
9
10
11
let code = 70

// Switch based on ranges.
switch code {
case 0...50:
print("Lower half")
case 51...100:
print("Upper half")
default:
print("Invalid")
}

Fallthrough Example

Fallthrough means that control proceeds to the next case in a switch, and the next case is entered even if the value does not match.

Output is below for the following example.

1
2
3
Number contains 2
Number contains 1
Number contains 0

Swift program that uses fallthrough statements

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let size = 2
// Use switch with fallthrough statements.
switch size {
case 3:
// This case will execute statements in case 2, 1 and 0.
print("Number contains 3")
fallthrough
case 2:
print("Number contains 2")
fallthrough
case 1:
print("Number contains 1")
fallthrough
case 0:
print("Number contains 0")
default:
print("Invalid")
}

String Example

Output is Is cat for the example below.

Swift program that uses switch on string

1
2
3
4
5
6
7
8
9
10
11
12
13
let name = "cat"

// Switch on the name string.
switch name {
case "bird":
print("Is bird")
case "dog":
print("Is dog")
case "cat":
print("Is cat") // This is printed.
default:
print("Something else")
}

Where Example

Where method can do further checking in some cases. For instance, we want to print out a tuple argument with a integer greater than 10. The following code output is below.

1
2
Default
Number = 15, Letter = b

Swift program that uses where in switch case

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func test(code: (Int, Character)) {
// Switch on the tuple argument.
// We use let to allow the tuple items to be referenced.
// We use where to test a part of the tuple.
switch code {
case let(number, letter) where number >= 10:
print("Number = \(number), Letter = \(letter)")
default:
print("Default")
}
}

// Call test with a tuple argument.
test(code: (5, "a"))
// Call test again.
test(code: (15, "b"))

Tuple Example

We use a “tuple pattern” to match all items in the tuple.

Output is Is xyz200 for the example below.

Swift that uses tuple switch

1
2
3
4
5
6
7
8
let data = ("xyz", 200)

// Match complete tuple values.
switch (data) {
case ("abc", 300): print("Is abc300")
case ("xyz", 200): print("Is xyz200")
default: print("Not known")
}

Let Values

A case block can capture values in a tuple switch. We use the “let” keyword and provide an identifier.

Output is Monkey has size 200 for the example below.

Swift that uses let, value switch

1
2
3
4
5
6
7
let value = ("monkey", 200)

// Use let to capture a variable in a tuple.
switch (value) {
case ("monkey", let size): print("Monkey has size \(size)")
default: break
}

Tuples With Any Value

With an underscore, we can match just parts of a tuple in a switch.

Output is Second value is 1 for the example below.

Swift that switches, matches any tuple value

1
2
3
4
5
6
7
8
9
let tuple = ("cat", 1, "penguin")

// Switch on tuple.
// ... Match second value of the tuple.
switch (tuple) {
case (_, 1, _): print("Second value is 1")
case (_, 2, _): print("Second value is 2")
default: print("No case")
}

Reference


This is the end of post

Markdown Cheat Sheet

Cheat Sheet

Markdown is a lightweight markup language with plain text formatting syntax, and it’s a good to write posts and articles in your blog.

Just found some cheat sheets for learning. Very helpful!

Check it out!

  1. Markdown CHEAT SHEET
  2. Markdown Cheatsheet

This is the end of post

How to define sub-cell under collectionView in Swift?

Question

In a collectionView, there are many cells. I want to run different code under different cells, what should I do?

Answer

The answer below is using Swift 3.

In collectionView, multiple cells can be defined by indexPath.row, you run different code with this variable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
if (collectionView == self.collectionView1) {

let cell : StandardCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseIdentifierStandard, for: indexPath) as! StandardCollectionViewCell

if indexPath.row == 0 {
print("your code")
cell.progressBar.progress = 0.2
} else if indexPath.row == 1 {
print("your code")
cell.progressBar.progress = 0.4
} else if indexPath.row == 2 {
print("your code")
cell.progressBar.progress = 0.6
}

return cell
}

This is the end of post

Machine Learning Note: Week 1

Course Information

Introduction

What is Machine Learning?

  1. A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P, if its performance at tasks in T, as measured by P, improves with experience E.

    Example: playing checkers.

  • E = the experience of playing many games of checkers
  • T = the task of playing checkers
  • P = the probability that the program will win the next game.
  1. In general, any machine learning problem can be assigned to one of two broad classifications: Supervised learning and Unsupervised learning.

Supervised Learning

  1. In supervised learning, we are given a data set and already know what our correct output should look like, having the idea that there is a relationship between the input and the output.
  2. Supervised learning problems are categorized into “regression” and “classification” problems.

Regression problems

In a regression problem, we are trying to predict results within a continuous output, meaning that we are trying to map input variables to some continuous function.

Regression - Given a picture of a person, we have to predict their age on the basis of the given picture.

Classification problems

In a classification problem, we are instead trying to predict results in a discrete output. In other words, we are trying to map input variables into discrete categories.

Classification - Given a patient with a tumor, we have to predict whether the tumor is malignant or benign.

Unsupervised Learning

Unsupervised learning allows us to approach problems with little or no idea what our results should look like. We can derive structure from data where we don’t necessarily know the effect of the variables. We can derive this structure by clustering the data based on relationships among the variables in the data. With unsupervised learning there is no feedback based on the prediction results.

Clustering

Take a collection of 1,000,000 different genes, and find a way to automatically group these genes into groups that are somehow similar or related by different variables, such as lifespan, location, roles, and so on.

Non-clustering

The “Cocktail Party Algorithm”, allows you to find structure in a chaotic environment. (i.e. identifying individual voices and music from a mesh of sounds at a cocktail party).

Model and Cost Function

Parameter Learning

Linear Algebra Review


This is the end of post

How to retrieve response headers with Alamofire in Swift?

Question

I’m using Alamofire to send a request to API, and API will send a reponse with headers. How can I retrive headers from it.

Answer

The answer below is using Swift 3.

1
2
3
4
Alamofire.request(.GET, requestUrl, parameters:parameters, headers: headers).responseJSON {
response in
print(response.response?.allHeaderFields)
}

response.response?.allHeaderFields contains all headers from the response.

If you want to get a certain value from headers, use response.response?.allHeaderFields[value] to get that header.

Reference


This is the end of post

How to check if UserDefaults key exists in Swift?

Question

I wanna check if any specific UserDefaults key exists in the application, how to start with it?

Answer

The answer below is using Swift 3.

1
2
3
func isKeyPresentInUserDefaults(key: String) -> Bool {
return UserDefaults.standard.object(forKey: key) != nil
}

When you use this function, simply create a variable by using

1
let checkIfCookieExist = userAlreadyExist(KeyName: defaultsKeys.KeyName)

it will return a boolean.

Reference


This is the end of post

这是一件让我觉得相见恨晚,物超所值的东西!

它是什么?

它是 WD 4TB My Cloud Personal Network Attached Storage,是一款 NAS 设置。你可以把它理解成一个「不能移动」的大容量硬盘,同时也可以作为整个家庭的娱乐终端,还可以作为一台没有显示器的微型电脑。我是在 Amazon 上购买,价格是 $170,附上购买链接

购买时选择 4TB 的容量就足够用,同时选择「Single Drive」。「Dual Drive」的价格要贵上一倍,「Single Drive」在破解后也可以添加「Dual Drive」的附加功能。

它有什么用?

这是一款 NAS 设置,运行的是 Linux 的系统,我是这样用它的。

  1. 将它作为 Time Machine 的备份机器。Macbook 上设置好了以后,会自动备份到 My Cloud 上。Time Machine 对于整个电脑备份堪称神器,随时都可以找回以前误删的资料。如果你有一种书到用时方恨少的感觉,Time Machine 就是那时刻应该出现的书。
  2. 将它作为 24 小时不停机的下载工具。在安装 Arial2 后,它可以为你 24 小时不停机的下载百度网盘上的电影,你再也不用将电脑开着下载资源了。
  3. 将它作为家庭影院的 Hub。在家中因为使用同一个 WiFi,这使得你可以随时方便地访问 My Cloud 上的数据。下载 VLC 播放器,你可以在任何移动设备 (iPhone, iPad, Android) 上播放 My Cloud 里面存放的电影。如果你使用智能电视或者 Apple TV 的话,你也可以下载 VLC 的应用程序,这样就可以直接在电视上播放 My Cloud 里的电影。
  4. 将它作为一个随时随地都可以访问的云端硬盘。下载 My Cloud 的app,或者登陆 http://www.mycloud.com/ 就可以在任何设备或者电脑上直接访问你所上传的资源,也可以下载到任何电脑上,同时还可以分享给你的朋友。

它有什么坏处?

  1. 它是 24 小时不停机运行的,意味着它有点耗电,但对于这样的一个小小的机器来说,电费应该不足挂齿。
  2. 百度网盘似乎针对 Arial2 下载有限速,我下载电影的速度只有 50 kb/s,这个速度实在太慢了。需要找找有没有什么办法可以移除下载速度限制的办法。

如何使用?

请参考以下几篇我撰写的攻略。

  1. 破解 WD MyCloud Gen2 安装第三方应用
  2. WD MyCloud 安装 Aria2 教程

This is the end of post

How to send POST request with parameters in Swift?

Question

I would like to send a POST request to an API with two parameters. How to start with it?

The API is https://www.google.com/
The parameters are

1
2
id = 1234
name = wei

Answer

Below is the example for Swift 3, you can follow with that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var request = URLRequest(url: URL(string: "https://www.google.com/")!)
request.httpMethod = "POST"
let postString = "id=1234&name=wei"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}

if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}

let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()

Reference


This is the end of post

How to save local data in Swift?

Question

I would like to save local data in my app, and need to use it sometime. The data could be a response from server.

The application is a swift-build application.

Answer

In Swift 3, we can use UserDefaults to handle local data. Below is the example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Setting

let defaults = UserDefaults.standard
defaults.set("One", forKey: defaultsKeys.keyOne)
defaults.set("Two", forKey: defaultsKeys.keyTwo)

// Getting

let defaults = UserDefaults.standard
if let stringOne = defaults.string(forKey: defaultsKeys.keyOne) {
print(stringOne) // One
}
if let stringTwo = defaults.string(forKey: defaultsKeys.keyTwo) {
print(stringTwo) // Two
}

Reference


This is the end of post