Swift基础
Swift语言相当灵活,这里做了一下总结,每个特性下面直接用代码做解释。
Variables
var languageName: String = "Swift"
let languageName: String = "Swift" //常量,安全性和运行速度有优势,所以优先考虑。
var version = 1.0 //推导为Double类型
var version: Double = 1.0
变量名可以使用Unicode符号,Emojo汉字都可以
String:
let someString = "String"
let components = "~/Documents/ZhaoZhe".pathComponents
// ["~", "Documents", "ZhaoZhe"]
Character:
for character in "Swift" {
println(character)
}
Combining Strings and Characters:
let china = "a"
let video = "好开心"
let chineseVideo = china + video
Building Complex Strings:
let a = 3, b = 5
let mathResult = "\(a) 乘以 \(b) 等于 \(a * b)"
\\3 乘以 5 等于 15
String Mutability:
var a = "小明"
a += "和小红"
Array and Dictionary:
let components = "~/Documents/ZhaoZhe".pathComponents
// ["~", "Documents", "ZhaoZhe"]
var names = ["ming", "hong", "sang", "four"]
var numberOfLegs = ["ant": 6, "snake": 0, "dog": 4]
var elements = Int[]()
Modify an Array:
var shoppingList = ["松花蛋", "doujiang"]
println(shoppingList[0])
shoppingList += "new"
shoppingList += ["new2", "new3"]
shoppingList[0] = "6颗松花蛋"
shoppingList[3...5] = ["毛豆", "黄瓜"]
Modify a Dictionary:
var numberOfLegs = ["ant": 6, "snake": 0, "dog": 4]
numberOfLegs["蜘蛛"] = 273 //自动添加这条
Retrieving a Value from a Dictionary:
possibleLegCount: Int? = numberOfLegs["章鱼"] //表示可能得到一个值,也可能没有值
if possibleLegCount == nil {
println("no data")
} else {
let legCount = possibleLegCount! //强制解包
println("一只章鱼\(legCount)条腿")
}
等价写法:
if possibleLegCount {
let legCount = possibleLegCount!
println("一只章鱼\(legCount)条腿")
}
等价写法:
if let legCount = possibleLegCount {
println("一只章鱼\(legCount)条腿")
}
If Stagements:
if legCount == 0 {
} else if letCount == 1 {
else {
}
Switch:
switch legCount {
case 0:
println("000")
break //写不写都会执行break
case 1, 3, 5, 7, 9:
println("111")
case 10...100:
println("222")
default:
println("nnn")
}
switch sender {
case button:
println("someone tapped button")
case usernameTextField:
println("someone tapped the text field")
default:
println("tapped something else")
}
Loops:
while !winCheck() {
next()
}
for var i = 1; i<=10; ++i {
}
for number in 1...5 {
//表示1~5所有值,如果是1..5就是1234,不包含5
}
var numberOfLegs = ["ant": 6, "snake": 0, "dog": 4]
for (animalName, legCount) in numberOfLegs {
println("一只\(animalName)\(legCount)条腿")
}
Functions:
func sayHello() {
println("Hello")
}
sayHello()
func sayHello(name: String = "路人甲") {
println("\(name) 你好")
}
sayHello() or sayHello(name: "zhaozhe")
func buildGreeting(name: String = "lurenjia") -> String {
return name + "Hello"
}
let greeting = buildGreeting()
//Return Multiple Values
func refreshWebPage() -> (Int, String) {
return (200, "Success")
}
let (statusCode, message) = refreshWebPage()
等价写法:
func refreshWebPage() -> (code: Int, message: String) {
return (200, "Success")
}
let status = refreshWebPage()
println("Received \(status.code): \(status.message)")
Tuples (元组)
//类似于没有名字的结构体
(2.79, 3.99, 4.19)
(404, "Not Found")
Closures: 闭包
let greetingPrinter = {
println("Hello World!")
}
等价写法:
let greetingPrinter: () -> () = {
println("Hello World!")
}
greetingPrinter()
Closure as Parameters:
func repeat(count: Int, task: () -> ()) {
for i in 0..count {
task()
}
}
repeat(2, {
println("Hello!")
})
Trailing Closures: 依附式闭包
repeat(2) {
println("Hello!")
}
Classes:
class Vehicle {
// properties
// methods
// initializers
var numberOfWheels = 0 //Stored Properties
//此处必须设置初始值,或者声明时加?
//Computed Properties
var description: String {
get { //get属性是默认的,不写这个声明也可以
return "\(numberOfWheels)个轮子"
}
set {
//在这里可以通过newValue变量访问新值
}
}
}
let someVehicle = Vehicle()
someVehicle.numberOfWheels = 2
println(someVehicle.description)
class Bicycle: Vehicle {
init() {
super.init() //这个不是必要的,子类初始化与父类无关
numberOfWheels = 2
}
}
let myBicycle = Bicycle()
Overriding a Property:
class Car: Vehicle {
var speed = 0.0
init() {
numberOfWheels = 4
}
override var description: String {
return super.description + ", 每小时 \(speed) 英里"
}
}
Property Observers: 属性观察
class ParentsCar: Car {
override var speed: Double {
willSet {
//这里可以通过newValue变量访问新值
if newValue > 65.0 {
println("请小心")
}
}
didSet {
//在这里可以通过oldValue变量访问旧值
}
}
}
Methods:
class Conter {
var count = 0
func increment(amount: Int) {
count += amount
}
func resetToCount(count: Int) {
self.count = count
}
}
Structures in Swift:
struct Point {
var x, y: Double
}
struct Size {
var width, height: Double
}
struct Rect {
var origin: Point
var size: Size
var area: Double {
return size.width * size.height
}
func isBiggerThanRect(other: Rect) -> Bool {
return self.area > other.area
}
}
var point = Point(x: 0.0, y: 0.0)
var size = Size(width: 640.0, height: 480.0)
var rect = Rect(origin: point, size: size)
Structures and Classes:
struct不可继承,class可以
struct在传输的时候是值传递,会复制整个值。class对象是引用传递,传递的是对象的引用
Constants and Variables: Reference Types
let window = Window(frame: frame) //Window是类
window.title = "Hello!" //这么做是可以的,因为window是个引用,即时是常量的引用也可以修改对象内的值
window = Window(frame: frame) //这样不可以
Constants and Variables: Value Types
let point1 = Point(x: 0.0, y: 0.0) //Point是结构体
point1.x = 5 //不可以这样做
Mutating a Structure:
struct Point {
var x, y: Double
mutating func moveToTheRightBy(dx: Double) { //mutating是在涉及到修改struct内部变量时必须的
x += dx
}
}
let point = Point(x: 0.0, y: 0.0)
point.moveToTheRightBy(200.0) //错误!!!
Enumerations: 枚举
enum Day: Int {
case Monday = 1
case Tuesday = 2
case Wdnesday = 3, Thursday = 4
}
等价写法:
enum Day: Int {
case Monday = 1, Tuesday, Wednesday, Thursday
}
let day = Day.thursday //推导为枚举Day类型
//day 是 Thursday
let dayNumber = Day.Thursday.toRow() //推导为其内部存储Int类型
//dayNumber 是 4
enum Direction {
case North, South, East, West
}
var direction = Direction.West
direction = .East
let lable = UILable()
lable.textAlignment = .Right
Enumerations: Associated Values
enum TrainStatus {
case OnTime, Delayed(Int)
init() {
self = OnTime
}
var description: String {
switch self {
case OnTime:
return "准时到达"
case Delayed(let minutes):
return "延误 \(minutes) 分钟"
default:
return "准时到达“”
}
}
}
var status = .Delayed(42)
println(status.description)
//延误 42 分钟
Nested Types: 类型嵌套
class Train {
enum Status {
case ......
......
}
}
Extensions: 扩展
extension Size {
mutating func increaseByFactor(factor: Int) {
width *= factor
height *= factor
}
}
extension Int {
func repetitions(task: () -> ()) {
for i in 0..self {
task()
}
}
}
500.repetitions({
println("赵哲"
})
Generic: 泛型
struct Stack<T> {
var elements = T[]()
mutating func push(element: T) {
elements.append(element)
}
mutating func pop() -> T {
return elements.removeLast()
}
}
var stringStack = Stack<String>()
stringStack.push("Hello")
println(stringStack.pop())