原文: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

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

Constants

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

Strings

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

Logical Operators

  1. var happy = true
  2. var sad = !happy // logical NOT, sad = false
  3. var everyoneHappy = happy && sad // logical AND, everyoneHappy = false
  4. var someoneHappy = happy || sad // logical OR, someoneHappy = true

Printing

  1. let name = "swift"
  2. println("Hello")
  3. println("My name is \(name)")
  4. print("See you ")
  5. print("later")
  6. /* Hello
  7. My name is swift
  8. See you later */

Arrays

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

Dictionaries

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

Conditionals

  1. //IF STATEMENT
  2. let happy = true
  3. if happy {
  4. println("We're Happy!")
  5. } else {
  6. println("We're Sad :('")
  7. }
  8. // We're Happy!
  9. let speed = 28
  10. if speed <= 0 {
  11. println("Stationary")
  12. } else if speed <= 30 {
  13. println("Safe speed")
  14. } else {
  15. println("Too fast!")
  16. }
  17. // Safe speed
  18. //SWITCH STATEMENT
  19. let n = 2
  20. switch n {
  21. case 1:
  22. println("It's 1!")
  23. case 2...4:
  24. println("It's between 2 and 4!")
  25. case 5, 6:
  26. println("It's 5 or 6")
  27. default:
  28. println("Its another number!")
  29. }
  30. // It's between 2 and 4!

For Loops

  1. for var index = 1; index < 3; ++index {
  2. // loops with index taking values 1,2
  3. }
  4. for index in 1..3 {
  5. // loops with index taking values 1,2
  6. }
  7. for index in 1...3 {
  8. // loops with index taking values 1,2,3
  9. }
  10. let colors = ["red", "blue", "yellow"]
  11. for color in colors {
  12. println("Color: \(color)")
  13. }
  14. // Color: red
  15. // Color: blue
  16. // Color: yellow
  17. let days = ["mon": "monday", "tue": "tuesday"]
  18. for (shortDay, longDay) in days {
  19. println("\(shortDay) is short for \(longDay)")
  20. }
  21. // mon is short for monday
  22. // tue is short for tuesday

While Loops

  1. var count = 1
  2. while count < 3 {
  3. println("count is \(count)")
  4. ++count
  5. }
  6. // count is 1
  7. // count is 2
  8. count = 1
  9. while count < 1 {
  10. println("count is \(count)")
  11. ++count
  12. }
  13. //
  14. count = 1
  15. do {
  16. println("count is \(count)")
  17. ++count
  18. } while count < 3
  19. // count is 1
  20. // count is 2
  21. count = 1
  22. do {
  23. println("count is \(count)")
  24. ++count
  25. } while count < 1
  26. // count is 1

Functions

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

Classes

  1. class Counter {
  2. var count: Int = 0
  3. func inc() {
  4. count++
  5. }
  6. func add(n: Int) {
  7. count += n
  8. }
  9. func printCount() {
  10. println("Count: \(count)")
  11. }
  12. }
  13. var myCount = Counter()
  14. myCount.inc()
  15. myCount.add(2)
  16. 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. C#中 String 格式的日期时间 转为 DateTime

    C#中并没有表示时间的变量,只有DateTime,所以要表示时间,可以用TimeSpan表示. 方法一:Convert.ToDateTime(string) string格式有要求,必须是yyyy-M ...

  2. 康乐不风流之爱解题的pde灌水王张祖锦

    康乐不风流之爱解题的pde灌水王张祖锦 师弟: 邓洪存 (现在烟台大学任教) 好吧, 我一直想写写康乐园里与我相熟的这几个人, 不如趁此机会开始. 第一批人物为张祖锦.苏延辉.张会春.黄显涛.刘兴兴. ...

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

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

  4. C#控件前缀命名规范

    标准控件 1  btn Button 2  chk CheckBox 3  ckl CheckedListBox 4  cmb ComboBox 5  dtp DateTimePicker 6  lb ...

  5. 32+激发灵感的HTML5/CSS3网页设计教程

      HTML5是寄托在HTML4基础上取得了的广泛成就.这不仅意味着你不必完全放弃现有的一些标记,而是可以借鉴,以加强 它. CSS3也以同样的方式在互联网内容的安排下,提供了它的柔韧性.CSS3是开 ...

  6. DOS 命令大全

    MS DOS 命令大全 一.基础命令 1 dir 无参数:查看当前所在目录的文件和文件夹. /s:查看当前目录已经其所有子目录的文件和文件夹. /a:查看包括隐含文件的所有文件. /ah:只显示出隐含 ...

  7. 200 OK (from cache) 与 304 Not Modified

    解释: 200 OK (from cache)  是浏览器没有跟服务器确认,直接用了浏览器缓存: 304 Not Modified 是浏览器和服务器多确认了一次缓存有效性,再用的缓存. 触发区别: 2 ...

  8. JS获得月最后一天和js得到一个月最大天数

    <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>标题页</title ...

  9. 《Java数据结构与算法》笔记-CH4-4循环队列

    /** * 循环队列 */ class Queue { private int maxSize; private long[] queue; private int front; private in ...

  10. 第三百四十九、五十天 how can I 坚持

    昨天是忘写博客了,今天下班才突然意思到,搞框架搞了好晚.今天重新下了个好了. 昨天,把存储过程交给同事写了,啥都不会,又一堆问题,折腾了一天. 今天相对轻松些,不过事情还没完..明天又周五了. 还有昨 ...