Notes and thoughts from Tony

Swift 4.0 快速参考手册

Comments

前言

马马虎虎过了两遍 Swift,语法还是容易忘,说明还是练得少。为了让练习的时候能够快速适应Swift的风格,根据 raywenderlichSwift 2.0 Cheat Sheet and Quick Reference整理了一份 Swift 快速参考手册。当然不会涉及到详细的用法,详细的用法已经有不少资料了。

更新:Swift 4.0 有几处更新。

废话不多说,依次过一遍。

类的实现

class MyClass : OptionalSuperClass,
OptionalProtocol1, OptionalProtocol2 {

	var myProperty:String
	var myOptionalProperty:String?
	// 其他属性

	// 子类覆盖父类的方法
	override init() {
		myProperty = "Foo"
	}

	// 其他方法
}

方法

func doIt() -> Int {
	return 0
}

func doIt(a:Int) -> Int {
	return a
}

func doIt(a:Int, b:Int) -> Int {
	return a + b
}

创建并使用一个实例(对象)

var a = MyClass()
a.myProperty
a.doIt()
a.doIt(a:1)
a.doIt(a:2, b:3)

枚举

//4.0 中枚举中的 case 都变成了小写
enum CollisionType: Int {
    case player = 1
    case enemy = 2
}
var type = CollisionType.player

变量声明

var mutableDouble:Double = 1.0
mutableDouble = 2.0

let constantDouble:Double = 1.0
// constantDouble = 2.0 // 错误,常量不可改变

var mutableInferredDouble = 1.0 //类型推断

var optionalDouble:Double? = nil //可选类型,初始化为nil
optionalDouble = 1.0

if let definiteDouble = optionalDouble { //可选绑定
	definiteDouble
}

强制解包

var myString:String?  //用问号声明可选变量
myString = "Hello, Swift!"

if myString != nil {
   print(myString) //结果: Optional("Hello, Swift!")
} else {
   print("myString has nil value")
}

if myString != nil {
   print(myString!) //结果: Hello, Swift!
} else {
   print("myString has nil value")
}

自动解包

var myString:String! //用感叹号声明可选变量,会自动解开
myString = "Hello, Swift!"

if myString != nil {
	print(myString)
} else {
   print("myString has nil value")
}

变量的种类

  • Int 1, 2, 500, 10000

  • Float和Double 1.5, 3.14, 578.234

  • Bool true, false

  • String “ibloodline”, “TonyHan”, “playground”

  • ClassName UIView, UIButton, etc

语句

var condition = true
if condition {
} else {
}

var val = 5
switch val {
case 1:
	"foo"
case 2:
	"bar"
default:
	"baz"
}

for i in 0..<3 {
}

字符串示例

var personOne = "ibloodline"
var personTwo = "TonyHan"
var combinedString = "\(personOne):Hello, \(personTwo)!"

var tipString = "2499"
var tipInt = NSString(string: tipString).intValue

tipString = "24.99"
var tipDouble = NSString(string: tipString).doubleValue

列表示例

var person1 = "ibloodline"
var person2 = "TonyHan"
var array:[String] = [person1, person2]
array.append("somebody")
for person in array {
    print("person: \(person)")
}
var p = array[2]

字典示例

var dict:[String: String] = ["name":"bloodline", "age": "875","sex": "male" ]
dict["addr"] = "Beijing"
dict["name"] = nil // 删除name
for (key, val) in dict {
    print("key: \(key), val:\(val)")
}