Swift for Complete Beginners

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

Enumerations

https://www.hackingwithswift.com/read/0/14/enumerations

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,743评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,296评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,285评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,485评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,581评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,821评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,960评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,719评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,186评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,516评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,650评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,329评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,936评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,757评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,991评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,370评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,527评论 2 349

推荐阅读更多精彩内容

  • Chapters: The Basics - Properties Excerpt From: Apple Inc...
    碧波浮沉阅读 597评论 0 1
  • 基础部分(The Basics) 当推断浮点数的类型时,Swift 总是会选择Double而不是Float。 结合...
    gamper阅读 1,275评论 0 7
  • 常量与变量使用let来声明常量,使用var来声明变量。声明的同时赋值的话,编译器会自动推断类型。值永远不会被隐式转...
    莫_名阅读 443评论 0 1
  • 今天收到儿子从部队邮来的东西。 这是他到部队一年第二次给家里邮东西。时间真快啊,一晃一年过去了。 儿子今年21,上...
    温暖鞍山阅读 217评论 0 0
  • 看到永澄老师今早推送的那篇文章《捷径并不是直路,而是阻力最小的路》很是触动。因为原来我也一直就是贪多的主儿。我们都...
    晓兰sally阅读 235评论 0 0