Swift语法快速索引

在WWDC的演示中就可以看出来Swift这个更接近于脚本的语言可以用更少的代码量完成和OC同样的功能。但是对于像我一样在战争中学习战争的同学们来说,天天抱着笨Swift Programming Language Reference之类的大部头看不实际。毕竟还是要养家糊口的。而且,那么1000+页内容讲的东西不是什么都要全部在平时工作中用到的。咱们就把平时用到的全部都放在一起,忘记了立马翻开看看,不知不觉的就学会了之后变成习惯。这样多省事。

变量

1 // Variable
2 var int_variable = 1    // 类型推断
3 var message : String
4 var x = 0.0, y = 0.0, z = 0.0

 

常量

// Constant
let const_int = 1
//const_int = 10  ERROR: can not assign to let value

 

字符串

Swift语法快速索引
// String
// 1. 定义
var empty_string = ""
var another_empty_string = String()
// 2. 拼接
var hello_string = "hello"
var world_string = " world"
hello_string += world_string    // hello world
 
let multiplier = 3
//let multiplier_message = "\(mulitplier) times 2.5 is \(Double(multiplier) * 2.5)"

// 3. 比较
var hello_world_string = "hello world"

hello_string == hello_world_string  // all are "hello world", result is true

if hello_string == hello_world_string {
    println("These two are equal")
}
Swift语法快速索引

 

Tuple

 

Swift语法快速索引
// Tuple
// 1. Unnamed tuple
let http_not_found = (404, "Not Found")
println("tuple item 1 \(http_not_found.0), tuple item 2 \(http_not_found.1)")
// 2. Named tuple
let (statusCode, statusMessage) = (404, "Not Found")
statusCode      // 404
statusMessage   // "Not Found"

let http_not_found2 = (statusCode:404, statusMessage:"Not Found")
http_not_found2.statusCode      // 404
http_not_found2.statusMessage   // "Not Found"
// 3. return tuple
func getHttpStatus() -> (statusCode : Int, statusMessage : String){
    // request http
    return (404, "Not Found")
}
Swift语法快速索引

 

 

数组

 

Swift语法快速索引
// Array

// 1. 定义
//var empty_array = []  // 在swift里没事不要这样定义数组。这是NSArray类型的,一般是Array<T>类型的
var empty_array : [Int]
var empty_array2 = [Int]()
var fire_works = [String]()
var colors = ["red", "yellow"]
var fires : [String] = ["small fire", "big fire"]; // Xcode6 beta3里数组的类型是放在方括号里的

var red = colors[0]

// 2. append & insert
colors.append("black")
colors += "blue"
colors += fires
colors.insert("no color", atIndex: 0)

// 3. update
colors[2] = "light blue"
//colors[5...9] = ["pink", "orange", "gray", "limon"]

// 4. remove
colors.removeAtIndex(5)
//colors[0] = nil ERROR!

// other
colors.isEmpty
colors.count
Swift语法快速索引

 

 

字典

 

 

Swift语法快速索引
// Dictionary
// 1. 定义
var airports : Dictionary<String, String> = ["TYP":"Tokyo", "DUB":"Boublin"]
var airports2 = ["TYP":"Tokyo", "DUB":"Boublin"]
var empty_dic = Dictionary<String, String>()
var empty_dic2 = [:]

// 2. update
airports.updateValue("Dublin International", forKey: "DUB")
airports["DUB"] = "Dublin International"

// 3. insert
airports["CHN"] = "China International"

// 4. check exists
if let airportName = airports["DUB"] {
    println("The name of the airport is \(airportName).")
}
else{
    println("That airport is not in the airports dictionary.")
}

// 5. iterate
for (airportCode, airportName) in airports{
    println("\(airportCode):\(airportName)")
}

// 6. remove
airports.removeValueForKey("TYP")
airports["DUB"] = nil
Swift语法快速索引

 

 

枚举

 

Swift语法快速索引
// Enum
// 1. defination & usage
enum PowerStatus: Int{
    case On = 1
    case Off = 2
}

enum PowerStatus2: Int{
    case On = 1, Off, Unknown
}

var status = PowerStatus.On

enum Barcode {
    case UPCA(Int, Int, Int)
    case QRCode(String)
}

var product_barcode = Barcode.UPCA(8, 8679_5449, 9)
product_barcode = .QRCode("ABCDEFGHIJKLMN")

switch product_barcode{
case .UPCA(let numberSystem, let identifier, let check):
    println("UPC-A with value of \(numberSystem), \(identifier), \(check)")
case .QRCode(let productCode):
    println("QR code with value of \(productCode)")
}
Swift语法快速索引

 

 

方法

 

 

Swift语法快速索引
// Function
// 1. 定义
func yourFuncName(){

}

// 2. 返回值
func yourFuncNameWithReturnType()->String{
    return ""
}

// 3. 参数
func funcWithParameter(parameter1:String, parameter2:String)->String{
    return parameter1 + parameter2
}

funcWithParameter("1", "2")

// 4. 外部参数名
func funcWithExternalParameter(externalParameter p1:String) -> String{
    return p1 + " " + p1
}

funcWithExternalParameter(externalParameter: "hello world")

func joinString(string s1: String, toString s2: String, withJoiner joiner: String)
    -> String {
        return s1 + joiner + s2
}

joinString(string: "hello", toString: "world", withJoiner: "&")

// 外部内部参数同名
func containsCharacter(#string: String, #characterToFind: Character) -> Bool {
    for character in string {
        if character == characterToFind {
            return true
        }
    }
    return false
}

containsCharacter(string: "aardvark", characterToFind: "v")

// 默认参数值
func joinStringWithDefaultValue(string s1: String, toString s2: String, withJoiner joiner: String = " ")
    -> String {
        return s1 + joiner + s2
}

joinStringWithDefaultValue(string: "hello", toString: "world") //joiner的值默认为“ ”

// inout参数
func swapTwoInts(inout a: Int, inout b: Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// prints "someInt is now 107, and anotherInt is now 3
Swift语法快速索引

 

 

 

 

Swift语法快速索引
// Class
// 1. 定义
class NamedShape {
    var numberOfSides: Int = 0
    var name: String
    
// *这样定义的初始化函数,其参数在调用的时候必须作为外名称使用 init(name: String) { self.name
= name }
// *这样定义的参数,在初始化的时候可以不使用外名称
init(_ nickName: String){
self.name = nickName
}
func simpleDescription()
-> String { return "A shape with \(numberOfSides) sides." } }

// 2. 继承 & 函数重载 & 属性getter setter class Square: NamedShape { var sideLength: Double init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func area() -> Double { return sideLength * sideLength } // 函数重载 override func simpleDescription() -> String { return "A square with sides of length \(sideLength)." } } class EquilateralTriangle: NamedShape { var sideLength: Double = 0.0 init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 3 } // 属性的getter setter var perimeter: Double { get { return 3.0 * sideLength } set { sideLength = newValue / 3.0 } } override func simpleDescription() -> String { return "An equilateral triagle with sides of length \(sideLength)." } } // 3. 使用 var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle") triangle.perimeter triangle.perimeter = 9.9 triangle.sideLength
Swift语法快速索引

 使用闭包给属性赋初值

Swift语法快速索引
struct Checkerboard {
    let boardColors: Bool[] = {
        var temporaryBoard = Bool[]()
        var isBlack = false
        for i in 1...10 {
            for j in 1...10 {
                temporaryBoard.append(isBlack)
                isBlack = !isBlack
            }
            isBlack = !isBlack
        }
        return temporaryBoard
        }()
    func squareIsBlackAtRow(row: Int, column: Int) -> Bool {
        return boardColors[(row * 10) + column]
    }
}
Swift语法快速索引

 

类(二)

1. 属性的初始化

2. init函数中修改常量属性

Swift语法快速索引
struct Color{
    // 在初始化函数中可以修改这些在定义时没有给出初始值的属性
    let red, green, blue: Double
    // stored property(就是下面这样定义的),如果是optional的(结尾时?活着!),可以在初始化函数
    // 中不给出初始值,否则必须给出初始值。
    var alpha: Double!
    
    init(r red: Double, green: Double, blue: Double){
        self.red = red
        self.green = green
        self.blue = blue
    }
    
    init(white: Double){
        red = white
        green = white
        blue = white
    }
    
    init(_ aColor: Double){
        self.red = aColor
        self.green = aColor
        self.blue = aColor
    }
}
Swift语法快速索引

3. 构造函数

Swift语法快速索引
// 默认init函数
class ShoppingItem {
    var name: String?
//    var quantity: Int // 编译错误,要使代码正确需要注释掉这一句
    var purchased = false
    
// 除非定义的属性全部都有初始值。optional的属性的默认值是nil。
// 否则的话必须显示定义一个init函数。
    init(){
        
    }
    
    init(name: String, purchased: Bool){
        self.name = name
        self.purchased = purchased
    }
    
    // 结构体等自定义值类型可以直接在一个init函数中使用self.init(...)的方式调用
    // 其他的init函数。但是在class(引用类型)中需要显示制定convenience关键字
    // 才可以调用其他的init函数
    convenience init(name: String){
        self.init(name: "hello", purchased: true)
    }
}

var item = ShoppingItem()

struct Color{
    // 在初始化函数中可以修改这些在定义时没有给出初始值的属性
    let red, green, blue: Double
    // stored property(就是下面这样定义的),如果是optional的(结尾时?活着!),可以在初始化函数
    // 中不给出初始值,否则必须给出初始值。
    var alpha: Double!
    
    init(r red: Double, green: Double, blue: Double){
        self.red = red
        self.green = green
        self.blue = blue
    }
    
    //在init函数中调用其他init函数
    init(white: Double){
//        red = white
//        green = white
//        blue = white
        self.init(r: 1.0, green: 2.0, blue:1.0)
    }
}
Swift语法快速索引

convenience的init函数只能在本类中调用。而一般的init函数(也就是designated init)可以在继承的链中在一个类中调用super类的init函数。

 

继承

不想什么被继承就在什么的前面放个final关键字(以前有@号,现在木有了)。如果在class前面放final关键字的话,那么整个类不可以被继承。

Swift语法快速索引
class ShoppingListItem: ShoppingItem{
    
    final var wishListed: Bool? // 不被继承
    
    override init(){
        super.init(name: "what", purchased: false)
    }
}
Swift语法快速索引

 

析构函数

Swift语法快速索引
class Vehicle{
    var numberOfWheels = 0
    var description: String{
        return "\(numberOfWheels) wheel(s)"
    }
    
    deinit{
        // 析构具体内容
    }
}
Swift语法快速索引

 

析构函数执行的特点:

1. 系统自动调用,不允许手动调用

2. 执行完本类调执行super类的

3. 执行完析构函数之后实例才释放,所以可以析构函数里可以访问全部属性的值

 

WEAK 和 UNOWNED关键字

Swift语法快速索引
class Customer{
    let name: String
    var card: CreditCard?
    init(name: String) {
        self.name = name
    }
}

class CreditCard{
    let number: Int
    /*
     * weak和owned关键字都用来修饰属性的,为了防止循环引用造成的内存无法释放。
     * 区别就在于unowned是一定要有值的。所以unowned只可以用在非可选类型上(non-optional type)
    */
    unowned let customer: Customer
    
    init(number: Int, customer: Customer){
        self.number = number
        self.customer = customer
    }
}
Swift语法快速索引

在闭包中也会出现这样的问题。如果在闭包中使用了self.xxxProperty也会出现对类实例本身的一个强引用,从而出现了循环引用。PS:在闭包中使用类成员的时候必须要用self.的写法。

Swift语法快速索引
    }
}

class HTMLElement {
    
    let name: String
    let text: String?
    
    lazy var asHTML: () -> String = {
        [unowned self] in
        if let text = self.text {
            return "<\(self.name)>\(text)</\(self.name)>"
        } else {
            return "<\(self.name) />"
        }
    }
    
    init(name: String, text: String? = nil) {
        self.name = name
        self.text = text
    }
    
    deinit {
        println("\(name) is being deinitialized")
    }
}
Swift语法快速索引

 

 

其他稍后补充

欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 330987132 | Go:217696290 | Python:336880185 | 做人要厚道,转载请注明出处!
上一篇:java性能优化方案10——考虑使用set而并非单个元素


下一篇:【Android 性能优化】应用启动优化 ( 安卓应用启动分析 | ActivityThread 主函数分析 | 应用初始化 | 启动优化项目 )