How to install Xcode and create a playground
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
Variables and constants
变量
var name = "Tim McGraw"
或
var name = "Tim McGraw"
name = "Romeo"
常量
import UIKit
let name = "Tim McGraw"
// name = "Romeo" 不要试图改变常量的值
Types of Data
先声明变量的类型,再赋值:
var name: String
name = "Tim McGraw"
var age: Int
age = 25
有小数部分的默认是 Double
var latitude: Double
latitude = 36.166667
var longitude: Float
longitude = -86.783333
var stayOutTooLate: Bool
stayOutTooLate = true
var missABeat: Bool
missABeat = false
类型推断:
var name = "Tim McGraw"
等价于
var name: String
name = "Tim McGraw"
或者,指定类型并赋值:
var name: String = "Tim McGraw"
Operators
加、减、乘、除、赋值分别对应:+
, -
, *
, /
, =
操作及赋值:+=
, -=
加一,减一:++
, --
比较:>
, >=
, <
等
判断:==
, !=
取反:!
String interpolation
var name = "Tim McGraw"
var name = "Tim McGraw"
"Your name is \(name)"
Arrays
var oddNumbers = [2, 4, 6, 8]
var songs = ["Shake it Off", "You Belong with Me", "Back to December"]
var songs = ["Shake it Off", "You Belong with Me", "Back to December"]
songs[0]
songs[1]
songs[2]
var songs = ["Shake it Off", "You Belong with Me", "Back to December"]
songs.dynamicType
var songs: [String]
songs[0] = "Shake it Off"
var songs: [String] = []
// 或
var songs = [String]()
数组操作:
var songs = ["Shake it Off", "You Belong with Me", "Love Story"]
var songs2 = ["Today was a Fairytale", "White Horse", "Fifteen"]
var both = songs + songs2
// 或
both += ["Everything has Changed"]
Dictionaries
var person = ["Taylor", "Alison", "Swift", "December", "taylorswift.com"]
var person = ["first": "Taylor", "middle": "Alison", "last": "Swift", "month": "December", "website": "taylorswift.com"]
person["middle"]
person["month"]
Conditional statements
var action: String
var person = "hater"
if person == "hater" {
action = "hate"
}
var action: String
var person = "hater"
if person == "hater" {
action = "hate"
} else if person == "player" {
action = "play"
} else {
action = "cruise"
}
var action: String
var stayOutTooLate = true
var nothingInBrain = true
if stayOutTooLate && nothingInBrain {
action = "cruise"
}
if !stayOutTooLate && !nothingInBrain {
action = "cruise"
}
Loops
for i in 1...10 {
print("\(i) x 10 is \(i * 10)")
}
var str = "Fakers gonna"
for _ in 1 ... 5 {
str += " fake"
}
print(str)
var people = ["players", "haters", "heart-breakers", "fakers"]
var actions = ["play", "hate", "break", "fake"]
for i in 0 ... 3 {
print("\(people[i]) gonna \(actions[i])")
}
var people = ["players", "haters", "heart-breakers", "fakers"]
var actions = ["play", "hate", "break", "fake"]
for i in 0 ..< people.count {
print("\(people[i]) gonna \(actions[i])")
}
var people = ["players", "haters", "heart-breakers", "fakers"]
var actions = ["play", "hate", "break", "fake"]
for i in 0 ..< people.count {
var str = "\(people[i]) gonna"
for _ in 1 ... 5 {
str += " \(actions[i])"
}
print(str)
}
使用 break
var counter = 0
while true {
print("Counter is now \(counter)")
++counter
if counter == 556 {
break
}
}
使用 continue
var songs = ["Shake it Off", "You Belong with Me", "Back to December"]
for song in songs {
if song == "You Belong with Me" {
continue
}
print("My favorite song is \(song)")
}
Switch case
let liveAlbums = 2
switch liveAlbums {
case 0:
print("You're just starting out")
case 1:
print("You just released iTunes Live From SoHo")
case 2:
print("You just released Speak Now World Tour")
default:
print("Have you done something new?")
}
let studioAlbums = 5
switch studioAlbums {
case 0...1:
print("You're just starting out")
case 2...3:
print("You're a rising star")
case 4...5:
print("You're world famous!")
default:
print("Have you done something new?")
}
Functions
定义
func favoriteAlbum() {
print("My favourite is Fearless")
}
调用
favoriteAlbum()
带参数
func favoriteAlbum(album: String) {
print("My favourite is \(album)")
}
带返回值
func albumsIsTaylor(name: String) -> Bool {
if name == "Taylor Swift" { return true }
if name == "Fearless" { return true }
if name == "Speak Now" { return true }
if name == "Red" { return true }
if name == "1989" { return true }
return false
}
Optionals
func getHaterStatus() -> String {
return "Hate"
}
func getHaterStatus() -> String? {
return "Hate"
}
func getHaterStatus(weather: String) -> String? {
if weather == "sunny" {
return nil
} else {
return "Hate"
}
}
var status: String
status = getHaterStatus("rainy")
var status: String?
status = getHaterStatus("rainy")
if let status = getHaterStatus("rainy") {
takeHaterAction(status)
}
强制转换,将 String?
换为 String!
Optional chaining
func albumReleasedYear(year: Int) -> String? {
switch year {
case 2006: return "Taylor Swift"
case 2008: return "Fearless"
case 2010: return "Speak Now"
case 2012: return "Red"
case 2014: return "1989"
default: return nil
}
}
let album = albumReleasedYear(2006)
print("The album is \(album)")
let album = albumReleasedYear(2006)?.uppercaseString
print("The album is \(album)")
let album = albumReleasedYear(2006)?.someOptionalValue?.someOtherOptionalValue?.whatever
let album = albumReleasedYear(2006) ?? "unknown"
print("The album is \(album)")