swift3.0基礎語法

swift 3.0 基礎語法

目錄

01-變量和常量

02-運算符

03-可選項

04-條件語句

05-循環

06-字符串

07-元組

08-數組

09-字典

10-對象和類

11-枚舉

12-屬性

13-下標腳本

01-變量和常量

1.1基本數據類型

    1.整數:  Int
    2.浮點數: Double表示64位浮點數,Float表示32位浮點數
    3.布爾類型: Bool,布爾值只有 true 和 false 兩種
    4.字符串: String
    5.字符: Character

1.2變量和常量

    1.變量:值能被修改,var 修飾
    2.常量:值不能被修改,let 修飾

var a = 20
a = 10
let b = 20
//b = 10  常量不能修改:error:'b' is a 'let' constant
    1.會自動推導聲明的變量或常量的屬性
    2.使用【option + 單擊】鍵查看屬性的類型
// 1.自動推導類型
let str = "ningcol"
let intValue = 10
let floatValue = 1.2

// 2.指定數據類型
let doubleValue:Double = 10

02-運算符

1基本運算符swift

var a = 5

let b = 3

  // 1.賦值運算符數組

  let c = bapp

  // 2.加減乘除ide

  1 + 2函數

  5 - 3學習

  2 * 3spa

  10.0 / 2.5code

2任何狀況下都不會作隱式轉化,必須以相同類型進行計算orm

let num1 = 1
let num2 = 2.2
let num3 = Double(num1) + num2

3必需要顯式類型的轉化對象

let j = 2.2
let i:Float = 1.2
i + Float(j)

4.求餘運算

a % b

5負號運算

let minusB = -b

6.組合賦值運算

a += 2

7.比較運算

1 == 1
2 != 1
2 > 1
1 < 2
1 >= 1
2 <= 1

8.三目運算

let d = a > b ? 100 : 200

9.空合運算

1.空合運算符( a ?? b )將對可選類型 a 進行空判斷(可選項內容詳見:04-可選項)

2.若是 aName nil,則執行??後面的,不然執行aName(注意??兩邊都有空格) 

var aName: String? = "ningcol"
//var aName: String? = nil
let bName = aName ?? "aNameIsNil"

10.區間運算

    1.閉區間運算符( a...b )定義一個包含從 a 到 b (包括 a 和 b )的全部值的區間
    2.半開區間( a..<b )定義一個從 a 到 b 但不包括 b 的區間

for index in 1...5 {

    print(index)

}

for index in 1..<5 {

    print("半開區間:\(index)")

}

11.邏輯運算

    1.邏輯非(!a):布爾值取反

    2.邏輯與( a && b ):只有 a b 的值都爲 true 時,整個表達式的值纔會是 true

    3.邏輯或( a || b ):兩個邏輯表達式的其中一個爲 tru e ,整個表達式就爲 true

let allowedEntry = false
let enteredDoorCode = true

if !allowedEntry {
    print("ACCESS DENIED")
}

if allowedEntry && enteredDoorCode {
    print("Welcome!")
} else {
    print("ACCESS DENIED")
}

if allowedEntry || enteredDoorCode {
    print("Welcome!")
} else {
    print("ACCESS DENIED")
}

03-可選項

1.可選值

可選值:能夠有值,能夠爲nil( ? 表示可選值)

// URL 爲可選項
let URL = NSURL(string: "http://www.baidu.com/")

// str 爲可選項
var str: String? = "ningcol"

// var 的可選項默認爲 nil
var a:Int?
print(a)

if let 語句

// if let : 確保 myUrl 有值,纔會進入分支
if let myUrl = URL{
    print(myUrl)
}

var aName: String? = "ningcol"
// var aName: String? = nil
var aAge: Int? = 18

if let name = aName,let age = aAge {
    print(name + String(age))
}
// 能夠對值進行修改
if var name = aName,let age = aAge {
    name = "lisi"
    print(name + String(age))
    
}

3.guard let

    1.guard let if let 相反。表示必定有值,沒有就直接返回

    2.下降分支層次結構

    3.playground不能展現效果,要在函數中展現

// 建立一個類(詳見:10-對象和類)
class test{
    func demo(){
        let aNick: String? = "ningcol"
        let aAge: Int? = 10
        guard let nick = aNick ,let age = aAge  else {
            print("nil")
            return
        }
        print("guard let: " + nick + String(age))
    }

}
var t = test()
t.demo()

4.強制解包

// 建立一個數組(詳見:08-組數)
var dataList:[String]?
dataList = ["zhangsan","lisi"]
/*********************************************************************
    1.dataList? 表示 datalist 可能爲 nil
    2.若是爲 nil, .count 不會報錯,仍然返回 nil
    2.若是不爲 nil,.count執行,返回數組元素個數
    4. ?? 空合運算符(詳見:02-運算符)
*********************************************************************/
let count = dataList?.count ?? 0

// 表示 datalist 必定有值,不然會出錯!
let cou = dataList!.count

04-條件語句

4.1.if語句

/*********************************************************************
    1.必需要有大括號
    2.沒有"非零即真"的概念,只有ture/false
*********************************************************************/
let num = 20
if num > 10{
    print("大於10");
}else{
    print("小於或等於10")
}

4.2switch

/*********************************************************************
    1.值能夠是任何類型
    2.做用域僅在 case 內部
    3.不須要 break
    4.每個 case 都要有代碼
*********************************************************************/
let name = "nick"

switch name {
case "nick":
    let age = 18
    print("one  \(age)")
case "fil":
    print("two")
case "Davi":
    print("three")
case "": break  //至關於有一行代碼
case "tom","ningcol":
    print("tomAndNingcol")
default:
    print("other")
}

 switch分支使用範圍

let count = 3_000
var naturalThings:String
switch count{
case 0:
    naturalThings = "數字0"
case 1...3:
    naturalThings = "數字1-3"
case 4...9:
    naturalThings = "數字4-9"
case 10...99:
    naturalThings = "數字10-99"
case 1000...9999:
    naturalThings = "數字1000-9999"
default:
    naturalThings = "數字9999以上"
}
print(naturalThings);

//輸出:數字1000-9999

 

05-循環

5.1 for循環

// 去掉了C語言風格的循環( ..< 區間運算符,詳見:02-預算符)
for i in 0..<10{
    print(i)
}

print("----步長循環-----")
// 遞增(步數爲2)
for i in stride(from: 0, to: 12, by: 2) {
    print(i)
}
print("開始遞減")
// 遞減
for i in stride(from: 12, to: 0, by: -2) {
    print(i)
}

print("----反序循環----")
let range = 0...10
// 反序循環
for i in range.reversed(){
    print(i)
}

5.2循環結構while

/*
 while語句,只有當 ip<5 爲 false 才跳出 while語句
 */
var  ip = 0
while (ip<5){ print("ip=\(ip)") ip += 1 } //運行結果 //ip=0 //ip=1 //ip=2 //ip=3 //ip=4 /* repeat-while 循環,無論pa是多少,先執行一次,在判斷,爲false 跳出 do while語句 */ var pa = 5 repeat{ print("pa=\(pa)") pa += 1 }while (pa<5) //運行結果 //pa=5

06-字符串

    1.String 結構體,效率比對象高,通常推薦使用,支持遍歷

    2.NSString 繼承NSObject

var str:String = "Hello你好"
//var st:NSString = "hah"
// 字節數量
print(str.lengthOfBytes(using: .utf8))
// 字符串長度
print(str.characters.count)
for a in str.characters{
    print(a)
}


// 字符串拼接
let name:String? = "老王"
let age = 80
let location = "隔壁"
print(location + (name ?? "a") + String(age) + "")
//  '\(變量名)' 會自動轉換拼接
print("\(location)\(name)\(age)歲")


let rect = CGRect(x: 0, y: 0, width: 100, height: 100)
print("\(rect)")

// 格式字符串
let h = 13
let m = 5
let s = 9
let timeStr = String(format: "%02d:%02d:%02d", arguments: [h,m,s])
let timeStr1 = String(format: "%02d:%02d:%02d", h,m,s)

    1.Swift中使用 Range,最好把 String 改爲 NSString

    2.str.substring(with: Range<String.Index>) 很麻煩

    3. ' as 類型' 做爲類型轉換

(str as NSString).substring(with: NSMakeRange(2, 5))

let index = str.index(str.startIndex, offsetBy: 3)
str.substring(from: index)
// "123"只是用來取到索引位置
str.substring(from: "123".endIndex)

print("****\(str.substring(from: "123".endIndex))")

str.substring(to: index)

String 使用 Range

let myRange = str.startIndex..<str.index(str.startIndex, offsetBy: 5)
str.substring(with: myRange)

let myRange1 = index..<str.index(str.startIndex, offsetBy: 5)
str.substring(with: myRange1)

07-元組

// 元組的元素個數固定,不容許增長、刪除
var stu = (404,"小白")
// 支持嵌套
var msg = ("基本信息", ("李剛",34))
print(stu)
print(msg)

var (a,b) = stu
print(a,b)
//若是僅須要元組中的個別的值,可使用"_"的方式來處理不須要的值
let (c,_) = stu
print(c)

//經過序號得到元組的值
print("status is \(stu.0)")

// 能夠修改
stu.0 = 500

let message = (status: 100, msg:"哈哈")
print("message is \(message.status)  and \(message.msg)")

08-數組

8.1 數組定義

 使用let修飾的數組是不可變數組

 使用var修飾的數組是可變數組

//方括號 [] 來建立數組
let array1 = ["zhangsan","lisi"]

let array2 = [1,2,3,4,5]

var array3:[Int] // 定義一個數組(沒有初始化)
array3 = [Int]() //初始化
//聲明空數組,(必須初始化)
let array4 = [String]()  // 等價上面兩行代碼

let array5:[Any] = ["zhangsan","lisi",20]

var arr3 = [Double](repeating: 0.0, count: 3) //[0.0, 0.0, 0.0]
var arr4 = Array(repeating: 3.0, count: 3)  //[3.0, 3.0, 3.0]

var arr: [String] = ["Alex", "Brian", "Dave"]
print(arr.count)
print(arr[0])

8.2數組遍歷

// forin方式
for name in array1{
    print(name)
}
// 遍歷數組
for i in 0..<array2.count{
    print(array2[i])
}

//區間遍歷
for item in array2[0..<2] {

    print("item\(item)")
}

// 同時遍歷下標和內容
print("=====同時遍歷下標和內容=====")
for e in array2.enumerated(){
    print(e)
    //offset 下標    element 值
    print("元組 \(e.offset) \(e.element)")
}

//下標和值同時遍歷
for (n, s) in array2.enumerated() {
    print(n, "===", s)
}

// 反序遍歷
for a in array2.reversed(){
    print(a)
}

// 遍歷下標和數值 反序

for (xxx,ooo) in array2.enumerated().reversed() {
    print(xxx,"==",ooo)
}

8.3數組增刪改

// 追加
arr.append("ningcol")

// 合併(類型必須一致)
let arr1 = ["Evi","Tank"]
arr += arr1

// 修改
arr[0] = "Tom"
print(arr)

// 刪除
arr.removeFirst()
print(arr)

//根據索引刪除
arr.remove(at: 2)
print(arr)

// 刪除所有並保留空間
arr.removeAll(keepingCapacity: true)
print(arr.capacity)  //數組容量

/***************************容量*************************/
// 容量每次都會在原來基礎上 * 2
print("初始容量 \(array3.capacity)")
for i in 0..<8{
    array3.append(i)
    print("--\(array3),容量:\(array3.capacity)")
}

09-字典

01字典定義

 

//方括號 [] 來建立字典

let dict1 = ["name":"lisi","age":"18"]
// 不一樣類型必須指明爲 any
var dict2:[String:Any] = ["name":"lisi","age":18]


let array = [
    ["name":"lisi","age":"18"],
    ["name":"wangwu","age":8]
]
print(array)
let array1:[[String:Any]] = [
    ["name":"lisi","age":"18"],
    ["name":"wangwu","age":8]
]
print(array1)

print(dict2["age"])

 

02字典增刪改

 

// 增長
dict2["sex"] = "man"
print(dict2)
// 修改(經過key來取值,key不存在就是新增)
dict2["name"] = "zhangsan"
print(dict2)
// 刪除(直接給key進行刪除)
dict2.removeValue(forKey: "age")
print(dict2)

03字典遍歷

for e in dict2{
    //e 爲元組
    print("字典遍歷:\(e)  e.key:\(e.key)  value:\(e.value)")
}
// key value 能夠隨意更改
for (key,value) in dict2{
    //e 爲元組
    print("key:\(key), value:\(value)")
}

04字典合併

var dict3:[String:Any] = ["name":"zhangsan","age":18,"sex":"man"]
let dict4:[String:Any] = ["name":"ningcol","height":50]
// 若是key存在修改  不存在會增長
for e in dict4{
    dict3[e.key] = dict4[e.key]
}
print("合併dict:" + String(format: "%@", dict3))

10-對象和類

// 建立一個類
class Shape {
    var numberOfSides = 0
    // 定義 simpleDescription 無參方法,返回值爲 String 類型
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

// 實例化
var shape = Shape()
// 賦值
shape.numberOfSides = 7
// 調用方法
var shapeDescription = shape.simpleDescription()

//  構造函數來初始化類實例
//如 oc : 
/*
 - (instanceType) initWithName:(NSString *)name;
 */
class NamedShape {
    var numberOfSides: Int = 0
    var name: String
    //自定義構造函數
    init(name: String) {
        //構造函數內的名字和類屬性名字同樣,須要使用 self 調用屬性
        self.name = name
    }
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

//let name = NamedShape(name: "name")
//name.simpleDescription()

重寫父類方法

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
    override func simpleDescription() -> String {
        return "A square with sides of length \(sideLength)."
    } }
let test = Square(sideLength: 5, name: "my test square")
test.area()
test.simpleDescription()

01-if let 語句

/*
 可選類型在每次訪問的時候都會提取並檢測它的值是否存在,但有時候根據程序結構能夠推斷可選量在首次賦值後必然存在值,這時候就不須要每次驗證值是否存在了,咱們可使用!進行強制隱式解包來獲取它的值,或者使用 if let 語句隱式解包
 */

//強制隱式解包
let possibleString: String? = "An optional string"
print(possibleString!)//解包,肯定 possibleString 值必定存在,不須要驗證

//隱式解包

if let value = possibleString {
    let stringValue = value
    
}

02-guard 語句

//grard 語句只會執行一個代碼塊
//guard 語句判斷其後表達式的布爾值爲 false 時纔會執行以後的代碼塊裏的代碼,若爲 true, 則跳過整個 guard 語句

//guard 函數只能用在函數裏面

func checkLogin(person: [String : String]) {
    
    //檢查帳號密碼,若是用戶名爲空,則不能登陸
    guard let uname = person["uname"] else {
        
        print("用戶爲空,不能登陸")
        return
    }
    //檢查帳號密碼,若是密碼爲空,則不能登陸
    guard let pawd = person["pawd"] else {
        
        print("密碼空,不能登陸!")
        return
    }
    
    //帳號和密碼都存在,方可進登陸
    print("用戶名:\(uname) 密碼:\(pawd)")
    print("登陸中請稍後...")
    
}

03-自定義構造函數

class Person: NSObject {
    var name : String?
    var age : Int = 0
    
    override init() {
        // 在構造函數中,若是沒有明確super.init(),那麼系統會幫助調用super.init()
        // super.init()
        
        print("------")
    }
    
    // 自定義構造函數不須要 override
    init(name : String, age : Int) {
        self.name = name
        self.age = age
    }
    
    //    init(dict : [String : AnyObject]) {
    //        let tempName = dict["name"]
    //        // tempName是一個AnyObject?,轉成String?
    //        // as? 最終轉成的類型是一個可選類型
    //        // as! 最終轉成的類型是一個肯定的類型
    //        name = tempName as? String
    //
    //
    //        /*
    //        let tempAge = dict["age"]
    //        let tempAge1 = tempAge as? Int
    //        if tempAge1 != nil {
    //            age = tempAge1!
    //        }
    //        */
    //
    
    //        if let tempAge = dict["age"] as? Int {
    //            age = tempAge
    //        }
    //    }
    
    //使用 KVC 必須先掉用 super.init()
    init(dict : [String : AnyObject]) {
        super.init()
        
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
}

//@interface Person : NSObject
//
//- (instanceType)initWithName:(NSString *)name age: (int)age
//- (instanceType)initWithDict:(NSDictionary *)dict;
//
//@end


let p = Person()
let p1 = Person(name: "why", age: 18)
print(p1.age)
print(p1.name)

let p2 = Person(dict: ["name" : "why" as AnyObject, "height" : 1.88 as AnyObject, "age" : 18 as AnyObject])
print(p2.age)
print(p2.name)

11-枚舉

枚舉定義

enum SomeEumeration {
    // 在這裏定義枚舉
}

//// 定義枚舉類型 指定類型
enum RequestType : String {
    case GET = "GET"
    case POST = "POST"
}

如下是地圖四個方向的一個例子:

enum MapDirection {
    case North
    case South
    case East
    case West
    
    func simpleDescription() -> String {
        switch self {
        case .North:
            return "North"
        case .South:
            return "South"
        case .East:
            return "East"
        case .West:
            return "West"
        default:
            return String("unknow")
        }
    }
}

//多個成員值能夠出如今同一行上,用逗號隔開:
enum MapDirection1 {
    case North,South,East,West
}

//枚舉的使用:枚舉名稱經過點語法獲枚舉的某一個取值
var directionToHead = MapDirection.West

//一旦directionToHead 被聲明爲一個 MapDirection類型,咱們可使用更短的點(.)語法將其設置爲另外一個 MapDirection 的值

12-屬性

/*
 1.存儲屬性
 2.計算屬性
 3.類屬性
 */

class Student: NSObject {
    // 定義存儲屬性
    var age : Int = 0
    var name : String?
    
    var mathScore : Double = 0.0
    var chineseScore : Double = 0.0
    
    // 定義計算屬性: 經過別的方式計算到結果的屬性,稱之爲計算屬性
    var averageScore : Double {
        return (mathScore + chineseScore) * 0.5
    }
    
    // 定義類型屬性: 類屬性是和整個類相關的屬性.並且是經過類名進行訪問
    /*
     兩種建立方法
     */
    //第一種方法
    static var courseCount : Int = 0
    
    //第二中方法
    class var newvalue: Int {
        return 10
    }
    
    /*
     // 定義方法,能夠返回平均成績
     func getAverageScore() -> Double {
     // 在swift開發中,若是使用當前對象的某一個屬性,或者調用當前對象的某一個方法時,能夠直接使用,不須要加self
     return (mathScore + chineseScore) * 0.5
     }
     */
}

// 給類屬性進行賦值
Student.courseCount = 2

// 建立對象
let stu = Student()

// 給對象的屬性賦值
stu.age = 10
stu.name = "yz"
stu.mathScore = 78
stu.chineseScore = 59.9

print(stu.age)
if let name = stu.name {
    print(name)
}

let averageScore = stu.averageScore

//使用類名調用,對象不能夠調用
Student.newvalue
Student.courseCount
/********************************************計算屬性***************************************/

/*枚舉、類、結構體除了擁有存儲屬性,還能夠定義計算屬性。
計算屬性不直接存儲值,而是提供一個getter和一個可選的setter來間接獲取、設置其餘屬性和變量的值。
 */

//便捷setter聲明 若是計算屬性的setter沒有定義表示新值的參數名,則能夠用默認值newValue,

//get:用來取值,封裝取值的過程
//set:用來設值,封裝設值的過程
// 下面定義三個結構體,來描述一個矩形
class Square {
        // 正方形的寬度
           var width: Double = 0.0
         // 正方形的周長
           var girth: Double {
                 get {
                         // 周長 = 寬度 * 4
                             return width * 4
                     }
                 set {
                         // 寬度 = 周長 / 4
                                width = newValue / 4
                     }
             }
     }
 var s = Square()//1
 s.width = 10//2
 print(s.girth)//3
 s.girth = 200//4
 print(s.width)//5
/*
 第3行代碼:調用girth屬性的get,輸出結果是40
 
 第4行代碼:調用girth屬性的set,而且把200傳遞給newGirth參數
 
 第5行代碼:輸出結果是50
 */


//只讀計算屬性 只有getter沒有setter的計算屬性
//只讀計算屬性老是返回一個值,能夠經過點語法訪問,可是不能設置
//只讀計算屬性能夠省略get和花括號
// 一個結構體 ,volume計算體積
struct Cuboid{
    var width = 0.0, height = 0.0, depth = 0.0
    var volume: Double{
        return width * height * depth
    }
}

let newCuboid = Cuboid(width: 3.0, height: 4.0, depth: 5.0)

/*注意
 1.由於計算屬性的值不是固定的,所以只能用var修飾計算屬性,不能用let
 2.一個屬性不能既是存儲屬性,又是計算屬性
 */

屬性的監視器

//屬性監視器能夠用來監控屬性值的變化,每次屬性被修改的時候都會被調用,即便新的值和舊的值同樣.
//一個屬性監視器由 willSet 和 didSet 組成, willSet 在設置新的值以前被調用,新的值做爲傳參,didSet 在新的值被設置以後調用,會將舊的屬性值做爲傳參.

class Person: NSObject {
    // 屬性監聽器
    var name : String? {
        // 屬性即將改變時進行監聽
        willSet {
            print(name)
            print(newValue)
        }
        
        // 屬性已經改變時進行監聽
        didSet {
            print(name)
            print(oldValue)
        }
    }
}


let p = Person()
p.name = "why"
p.name = "yz"

13-下標腳本

//下標腳本
//swift 經過索引快速取值的一種語法.例如數組的a[0]就是一個下標腳本,經過索引0 快速取值,咱們能夠在類,結構體,和枚舉中本身定義下標腳本
//下標腳本使用subscript 關鍵字來定義 經過 get ,set 來定義讀,寫屬性,能夠只有 get 只讀方法.定義
//set 屬性時,傳入的參數類型和subscript 函數返回的值必須相同
/**subscript(參數名稱1: 數據類型, 參數名稱2: 數據類型,...)-> 返回值的數據類型 {

     get {
         //返回與參數類型同樣的值
     } set (參數名稱){
         // 執行相關的賦值操做
     }
}
*/
//代碼以下:

class Experience {
    var age: [Int] = Array(repeating: 0,count: 5)
    subscript(index:Int) -> Int {
    
        get {
        
            return age[index]
            
        }set {
        
            age[index] = newValue
        }
    }
}
//能夠經過下標腳原本設置獲取某一屬性的值
var ex = Experience()
//設置第一個腳標的值爲5
ex[0] = 5
ex[1] = 6
print(ex[0])
print(ex[1])

/**
 
 下標腳本能夠和計算屬性同樣設置爲讀寫或只讀,也就是定義下標腳本時不設置 set 方法,上面的代碼是讀寫形式,下面就使用只讀的形式實現使用下標訪問屬性值的功能
 */

class Experience2 {
    
    var age2: [Int] = Array(repeating: 0,count: 5)
    
    subscript(index:Int) -> Int {
        
        get {
            
            return age2[index]
            
        }
    }
}

//這種狀況下,咱們只能獲取屬性值,不能對屬性設置值.獲取屬性值的代碼以下

var ex2 = Experience2()
let e0 = ex2[0]
let e1 = ex2[1]

print(e0)
print(e1)

 

/****************************************************

對以前學習的swift 語法又複習了一下,此文轉載簡書做者:ningcol 連接:http://www.jianshu.com/p/1c25105bba4f  能夠去原做者文章中下載 demo,這裏我在原做者文章中又補充了一些基礎知識.

***************************************************************/

相關文章
相關標籤/搜索