原文:http://kpbp.github.io/swiftcheatsheet/

A quick cheat sheet and reference guide for Apple's Swift language. This guide intends to cover all the key features of Swift, including Strings, Arrays, Dictionaries and Flow Control.

Swift is a new programming language for developing iOS and OS X apps that was introduced by Apple in June 2014.

Variables

var myInt = 1
var myExplicitInt: Int = 1 // explicit type
var x = 1, y = 2, z = 3 // declare multiple integers
myExplicitInt = 2 // set to another integer value

Constants

let myInt = 1
myInt = 2 // compile-time error!

Strings

var myString = "a"
let myImmutableString = "c"
myString += "b" // ab
myString = myString + myImmutableString // abc
myImmutableString += "d" // compile-time error! let count = 7
let message = "There are \(count) days in a week"

Logical Operators

var happy = true
var sad = !happy // logical NOT, sad = false
var everyoneHappy = happy && sad // logical AND, everyoneHappy = false
var someoneHappy = happy || sad // logical OR, someoneHappy = true

Printing

let name = "swift"
println("Hello")
println("My name is \(name)")
print("See you ")
print("later")
/* Hello
My name is swift
See you later */

Arrays

var colors = ["red", "blue"]
var moreColors: String[] = ["orange", "purple"] // explicit type
colors.append("green") // [red, blue, green]
colors += "yellow" // [red, blue, green, yellow]
colors += moreColors // [red, blue, green, yellow, orange, purple] var days = ["mon", "thu"]
var firstDay = days[0] // mon
days.insert("tue", atIndex: 1) // [mon, tue, thu]
days[2] = "wed" // [mon, tue, wed]
days.removeAtIndex(0) // [tue, wed]

Dictionaries

var days = ["mon": "monday", "tue": "tuseday"]
days["tue"] = "tuesday" // change the value for key "tue"
days["wed"] = "wednesday" // add a new key/value pair var moreDays: Dictionary<string, string=""> = ["thu": "thursday", "fri": "friday"]
moreDays["thu"] = nil // remove thu from the dictionary
moreDays.removeValueForKey("fri") // remove fri from the dictionary

Conditionals

//IF STATEMENT
let happy = true
if happy {
println("We're Happy!")
} else {
println("We're Sad :('")
}
// We're Happy! let speed = 28
if speed <= 0 {
println("Stationary")
} else if speed <= 30 {
println("Safe speed")
} else {
println("Too fast!")
}
// Safe speed //SWITCH STATEMENT
let n = 2
switch n {
case 1:
println("It's 1!")
case 2...4:
println("It's between 2 and 4!")
case 5, 6:
println("It's 5 or 6")
default:
println("Its another number!")
}
// It's between 2 and 4!

For Loops

for var index = 1; index < 3; ++index {
// loops with index taking values 1,2
}
for index in 1..3 {
// loops with index taking values 1,2
}
for index in 1...3 {
// loops with index taking values 1,2,3
} let colors = ["red", "blue", "yellow"]
for color in colors {
println("Color: \(color)")
}
// Color: red
// Color: blue
// Color: yellow let days = ["mon": "monday", "tue": "tuesday"]
for (shortDay, longDay) in days {
println("\(shortDay) is short for \(longDay)")
}
// mon is short for monday
// tue is short for tuesday

While Loops

var count = 1
while count < 3 {
println("count is \(count)")
++count
}
// count is 1
// count is 2 count = 1
while count < 1 {
println("count is \(count)")
++count
}
// count = 1
do {
println("count is \(count)")
++count
} while count < 3
// count is 1
// count is 2 count = 1
do {
println("count is \(count)")
++count
} while count < 1
// count is 1

Functions

func iAdd(a: Int, b: Int) -> Int {
return a + b
}
iAdd(2, 3) // returns 5 func eitherSide(n: Int) -> (nMinusOne: Int, nPlusOne: Int) {
return (n-1, n+1)
}
eitherSide(5) // returns the tuple (4,6)

Classes

class Counter {
var count: Int = 0
func inc() {
count++
}
func add(n: Int) {
count += n
}
func printCount() {
println("Count: \(count)")
}
} var myCount = Counter()
myCount.inc()
myCount.add(2)
myCount.printCount() // Count: 3

[转]Swift Cheat Sheet的更多相关文章

  1. 转:PostgreSQL Cheat Sheet

    PostgreSQL Cheat Sheet CREATE DATABASE CREATE DATABASE dbName; CREATE TABLE (with auto numbering int ...

  2. Git Cheat Sheet

    Merge Undo git merge with conflicts $ git merge --abort Archive $ git archive --format zip --output ...

  3. CSS3 Animation Cheat Sheet:实用的 CSS3 动画库

    CSS3 Animation Cheat Sheet 是一组预设的动画库,为您的 Web 项目添加各种很炫的动画.所有你需要做的是添加样式表到你的网站,为你想要添加动画效果的元素应用预制的 CSS 类 ...

  4. XSS (Cross Site Scripting) Prevention Cheat Sheet(XSS防护检查单)

    本文是 XSS防御检查单的翻译版本 https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sh ...

  5. IOS Application Security Testing Cheat Sheet

    IOS Application Security Testing Cheat Sheet    [hide]  1 DRAFT CHEAT SHEET - WORK IN PROGRESS 2 Int ...

  6. XSS Filter Evasion Cheat Sheet 中文版

    前言 译者注: 翻译本文的最初原因是当我自己看到这篇文章后,觉得它是非常有价值.但是这么著名的一个备忘录却一直没有人把它翻译成中文版.很多人仅仅是简单的把文中的 各种代码复制下来,然后看起来很刁的发在 ...

  7. HTML5 Cheat sheet PNG帮助手册(标签、事件、兼容)

    HTML5 Cheat sheet PNG帮助手册(标签.事件.兼容) 1.HTML5标签 2.HTML5事件 3.HTML5兼容 最新HTML5手册资料请参考:http://www.inmotion ...

  8. The iOS Design Cheat Sheet 界面设计速参

    http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/ With the release of iOS 7, app designers ...

  9. Windows平台Atom编辑器的常用快捷键小抄Cheat Sheet

    博客搬到了fresky.github.io - Dawei XU,请各位看官挪步.最新的一篇是:Windows平台Atom编辑器的常用快捷键小抄Cheat Sheet.

随机推荐

  1. Supervisor行为分析和实践

    1.简介     Erlang要编写高容错性.稳定性的系统,supervisor就是用来解决这一问题的核心思想.通过建立一颗监控树,来组织进程之间的关系,通过确定重启策略.子进程说明书等参数信息来确定 ...

  2. [Papers]NSE, $u$, Lorentz space [Sohr, JEE, 2001]

    $$\bex \bbu\in L^{p,r}(0,T;L^{q,\infty}(\bbR^3)),\quad\frac{2}{p}+\frac{3}{q}=1,\quad 3<q<\inf ...

  3. XSS跨站及利用

    (一)软件测试环境以及搭建 测试环境:本地 XAMPP 1.7.1 测试软件:PHP168整站v5.0 软件下载地址 http://down2.php168.com/v2008.rar PHP.ini ...

  4. Collectl基础

    Collectl比nmon更专业和深入的linux性能测试工具 首先是安装 $ sudo apt-get install collectl 直接输入collectl就可以看到数据 默认是CPU,硬盘, ...

  5. 用ASP.Net写一个发送ICQ信息的程序

    用ASP.Net写一个发送ICQ信息的程序 这里我给大家提供一个很实用的例子,就是在线发送ICQ信息.想一想我们在网页上直接给朋友发送ICQ信息,那是多么美妙的事情啊.呵呵,在吹牛啊,其实ICQ本来就 ...

  6. 如何解决grails2.3.2中不能运行fork模式

    升级到grails 2.3.2之后,运行时报如下的异常: Exception in thread "main" Error | Forked Grails VM exited wi ...

  7. linux c多线程编程范例

    #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h& ...

  8. nodejs cmd

    引入系统模块 var exec = require('child_process').exec; cmd.js var exec = require('child_process').exec; va ...

  9. HDU 2042 不容易系列之二 [补6.24] 分类: ACM 2015-06-26 20:40 9人阅读 评论(0) 收藏

    不容易系列之二 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Su ...

  10. HD2046骨牌铺方格

    骨牌铺方格 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submiss ...