1. 程式人生 > >初探swift語言的學習筆記七(swift 的關健詞)

初探swift語言的學習筆記七(swift 的關健詞)

作者:fengsh998原文地址:http://blog.csdn.net/fengsh998/article/details/32133809轉載請註明出處如果覺得文章對你有所幫助,請通過留言或關注微信公眾帳號fengsh998來支援我,謝謝!

每一種語言都有相應的關鍵詞,每個關鍵詞都有他獨特的作用,來看看swfit中的關鍵詞:

    關鍵詞:

用來宣告的:

“ class, deinit, enum, extension, func, import, init, let, protocol, static, struct, subscript, typealias, var.”

用於子句的:

“ break, case, continue, default, do, else, fallthrough, if, in, for, return, switch, where, while.”

表示式和型別的:

“ as, dynamicType, is, new, super, self, __COLUMN__, __FILE__, __FUNCTION__, __LINE__”

//特殊語境使用的:

“didSet, get, inout, mutating, override, set, unowned, unowned(safe), unowned(unsafe), weak , willSet”


class

用來定義一個類,相信大家並不陌生。

如果定義一個汽車類

class Car
{
      init()
      {
            //to do init something.
       }
}

init

相對於類的構造方法的修飾。

deinit

相對於類的釋構方法的修飾。

對於類的構造和釋構在swift 中需要使用關鍵詞來修飾,而很多高階語言並不需要特別的指定,便C++ 只需要類名與建構函式名相同就可以,不需要額外的關鍵詞。

enum

 列舉型別的宣告,這個與很多語方都相通。

extension

擴充套件,有點像oc中的categories 。

Swift 中的可以擴充套件以下幾個:
新增計算型屬性和計算靜態屬性
定義例項方法和型別方法
提供新的構造器
定義下標
定義和使用新的巢狀型別
使一個已有型別符合某個介面

如下面擴充套件字串:

extension String{
    struct _Dummy {
        var idxVal: Int
        var _padding: Int
        var _padding2: Int
        var _padding3: Int
    }
    //過慮出數字
    func fitlerCharater() -> String
    {
        var numberstr : String = ""
        for character in self
        {
            let s :String = String(character)
            
            //println(s.toInt())
            if let hs = s.toInt()
            {
                numberstr += character
            }
        }
        return numberstr
    }
    
    //擴充套件使用下標訪問
    subscript (i: Int) -> Character {
        var dummy: _Dummy = reinterpretCast(i >= 0 ? self.startIndex : self.endIndex)
            dummy.idxVal += i
            let idx: String.Index = reinterpretCast(dummy)
            return self[idx]
    }
    
    //擴充套件使用Range訪問
    subscript (subRange: Range<Int>) -> String {
        var start: _Dummy = reinterpretCast(self.startIndex)
            var end = start
            start.idxVal = subRange._startIndex
            end.idxVal = subRange._endIndex
            let startIndex: String.Index = reinterpretCast(start)
            let endIndex: String.Index = reinterpretCast(end)
            return self[startIndex..endIndex]
    }
}

測試:
func testExtension()
{
    var str : String = "1234ab5國6cd7中8i90"
    println(str.fitlerCharater())
    
    let china: String = "china operating system public to 世界"
    println("使用下標索引訪問第13個字元 \(china[13])")
    println("使用負號下標即變為從右往左訪問字元 \(china[-1])")
    println("使用負號下標即變為從右往左訪問字元 \(china[-2])")
    println("使用下標Range來訪問範圍 \(china[2...6])")
    dump(china[1..5], name: "china[1:4]")              //使用dump輸出
    dump(china[10...13], name: "china[10:13]")
}

輸出:
1234567890
使用下標索引訪問第13個字元 n
使用負號下標即變為從右往左訪問字元 界
使用負號下標即變為從右往左訪問字元 世
使用下標Range來訪問範圍 ina o
- china[1:4]: hina
- china[10:13]: atin

func

 用來修飾函式的關鍵詞。

import

 匯入標頭檔案,相信大家都不陌生,但在swift 中好像被用來匯入包,如import UIKit。 因為swift中沒有了標頭檔案的概念。

let

用來修改某一常量的關鍵詞。像const 限定差不多

var

用來宣告變數。

protocol

協議,也有稱為介面,這個往往在很多高階語言中不能多重繼承的情況下使用協議是一個比較好的多型方式。

static

用來修飾變數或函式為靜態

struct

用來修飾結構體。

subscript

下標修飾,可以使類(class),結構體(struct),列舉(enum) 使用下標訪問。
class Garage
{
    var products : String[] = Array()
    
    subscript(index:Int) -> String
    {
        get
        {
            return products[index]
        }
        
        set
        {
            if index < products.count  //&& !products.isEmpty
            {
                products[index] = newValue
            }
            else
            {
                products.append(newValue)
            }
            
        }
    }
}

測試:
func testSubscript()
{
    var garage = Garage()
    garage[0] = "A"
    garage[1] = "B"
    garage[2] = "C"
    garage[3] = "D"
    garage[2] = "CC"
    
    println("index 1 = \(garage[0]) ,index 2 = \(garage[1]),index 3 = \(garage[2]) ,index 4 = \(garage[3])")
}

輸出
index 1 = A ,index 2 = B,index 3 = CC ,index 4 = D

typealias

類型別名,就像typedef一樣。借typedef  unsigned long int    UInt64 

同樣在swift中也可能自定義型別。

break

跳出迴圈,通常用於for,while,do-while,switch 

case

case相信大家並不陌生,常在switch中使用,但如今在swift中多了一個地方使用哪就是列舉型別。

continue

跳過本次迴圈,繼續往後執行。

default

預設宣告。常見在switch中。

do, else,if, for, return, switch, while

這幾個就不用多說了,越說越混。

in

範圍或集合操作

let str = "123456"
for c in str
{
     println(c)
}

fallthrough

由於swift中的switch語句中可以省去了break的寫法,但在其它語言中省去break裡,會繼續往後一個case跑,直到碰到break或default才完成。在這裡fallthrough就如同其它語言中忘記寫break一樣的功效。

        let integerToDescribe = 1
        var description = "The number \(integerToDescribe) is"
        switch integerToDescribe {
        case 1, 3, 5, 7, 11, 13, 17, 19:
            description += " a prime number, and also";
            fallthrough
        case 5:
            description += " an integer"
        default :
            description += " finished"
        }
        
        println(description)

輸出:
The number 1 is a prime number, and also an integer

where

swift中引入了where 來進行條件判斷。

let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
println("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
println("(\(x), \(y)) is on the line x == -y")
case let (x, y):
println("(\(x), \(y)) is just some arbitrary point")
}

當switch的條件滿足where 後面的條件時,才執行語句。

is

as

is 常用於對某變數型別的判斷,就像OC中 isKindClass ,as 就有點像強制型別轉換的意思了。

        for view : AnyObject in self.view.subviews
        {
            if view is UIButton
            {
                let btn = view as UIButton;
                println(btn)
            }
        }

OC的寫法:
for (UIView *view  in self.view.subviews)
{
      if ([view isKindOfClass:[UIButton class]])         //is 操作
     {
             UIButton *btn =(UIButton *)view             //as 操作
      }
}

super

基類的關鍵語,通常稱父類

__COLUMN__, __FILE__, __FUNCTION__, __LINE__

是不是有點像巨集定義啊。

println(__COLUMN__ ,__FILE__, __FUNCTION__, __LINE__)

輸出:
(17, /Users/apple/Desktop/swiftDemo/swiftDemo/ViewController.swift, viewDidLoad(), 62)

set,get

常用於類屬性的setter getter操作。

willSet,didSet

在swift中對set操作進行了擴充套件,willset 在set新值成功前發生,didset在設定新值成功後發生。

inout

對函式引數作為輸出引數進行修飾。

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

mutating

具體不是很理解,好像是專為結構體使用而設定的變體宣告
protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

class SimpleClass: ExampleProtocol {
    var simpleDescription: String = "A very simple class."
    func adjust() {
        simpleDescription += "  Now 100% adjusted."
    }
}


struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple structure"
    mutating func adjust() {                //如果去除mutating 報Could not find an overload for '+=' that accepts the supplied arguments
        simpleDescription += " (adjusted)"
    }
}
測試
func testMutating()
{
    var a = SimpleClass()
    a.adjust()
    let aDescription = a.simpleDescription
    println(aDescription)
    
    var b = SimpleStructure()
    b.adjust()
    let bDescription = b.simpleDescription
    println(bDescription)
}
override
父子類之間的函式重寫,即覆蓋。

unowned, unowned(safe), unowned(unsafe)

無宿主引用。

[unowned self] 或[unowned(safe) self] 或[unowned(unsafe) self]

weak

弱引用,使得物件不會被持續佔有