swift小筆記

1、一行中聲明多個變量或常量,用逗號分隔

var x = 0.0, y = 0.0, z = 0.0

var red, green, blue: Double

2、推薦使用 Double 類型、Int類型。

3、Int(string)返回一個可選的 Int ,而不是 Int ??蛇x的 Int 寫做 Int? ,而不是 Int 。問號明確了它儲存的值是一個可選項,意思就是說它可能包含某些 Int 值,或者可能根本不包含值。(他不能包含其他的值,例如 Bool 值或者 String 值。它要么是 Int 要么什么都沒有。)

let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// convertedNumber is inferred to be of type "Int?", or "optional Int"

4、通過給可選變量賦值一個 nil 來將之設置為沒有值,在函數(shù)參數(shù)使用時可以把參數(shù)定義為可選項,然后給默認值為nil,來在調(diào)用時省略參數(shù)

var serverResponseCode: Int? = 404
// serverResponseCode contains an actual Int value of 404
serverResponseCode = nil
// serverResponseCode now contains no value

    func requestData(_ itemIds:[String]? = nil, _ month:Int? = nil, _ year:Int? = nil, _ state:Int? = nil) {
   ////////
    }

調(diào)用 requestData()

5、善用 if let 、guard let 可選綁定的關鍵字

guard let constantName = optionalValue else {
    // optionalValue 不包含值的情況,提前返回或處理錯誤。
    // 必須在此處退出當前函數(shù)、循環(huán)或代碼塊
}
// 在此處使用 constantName,它是一個非可選的值


let optionalName: String? = "Alice"
if let name = optionalName {
    print("Hello, \(name)!")  // 輸出 "Hello, Alice!"
} else {
    print("The name is missing.")
}

6、通過檢查布爾量 isEmpty屬性來確認一個 String值是否為空

var emptyString = ""               // empty string literal
var anotherEmptyString = String()  

if emptyString.isEmpty {
    print("Nothing to see here")
}
// prints "Nothing to see here"

7、范型

函數(shù)使用

// 指明函數(shù)的泛型參數(shù)(形式參數(shù))需要使用'T'這個類型(T自己定義的一個類型)
func swapTwoValues<T>(_ a: T, _ b: T)

除了泛型函數(shù),Swift允許你定義自己的泛型類型。它們是可以用于任意類型的自定義類、結構體、枚舉,和 Array 、 Dictionary 方式類似。

struct IntStack {
    var items = [Int]()
    mutating func push(_ item: Int) {
        items.append(item)
    }
    mutating func pop() -> Int {
        return items.removeLast()
    }
}

用泛型改寫:
struct Stack<Element> {
    var items = [Element]()
    mutating func push(_ item: Element) {
        items.append(item)
    }
    mutating func pop() -> Element {
        return items.removeLast()
    }
}

使用實例
通過在尖括號中寫出存儲在棧里的類型,來創(chuàng)建一個新的 Stack 實例。例如,創(chuàng)建一個新的字符串棧,可以寫 Stack<String>() :
var stackOfStrings = Stack<String>()
stackOfStrings.push("uno")
stackOfStrings.push("dos")
stackOfStrings.push("tres")
stackOfStrings.push("cuatro")
// the stack now contains 4 strings

8、循環(huán) for-in 、forEach、(while、repeat-while 了解)

// 數(shù)組
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print("Hello, \(name)!")
}

??map 和 forEach 是 Swift 中用于處理序列(比如數(shù)組)的兩個常見方法
map 轉換每個元素并生成新的序列,而 forEach 只是對每個元素進行操作,不返回新序列(簡單的來說就是map有返回值,forEach無返回值)。
??map 和 forEach使用如下:
============================================
let numbers = [1, 2, 3, 4, 5]
// 使用 map 轉換每個元素,并返回一個新的序列
let multipliedByTwo = numbers.map { $0 * 2 }
print(multipliedByTwo) // 輸出 [2, 4, 6, 8, 10]

// 使用 forEach 對每個元素執(zhí)行操作
numbers.forEach { print($0) } // 輸出 1 2 3 4 5

=============================================


// 字典
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs")
}

// 角標
for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}

let minutes = 60
for tickMark in 0..<minutes {
    // render the tick mark each minute (60 times)
}

// stride 函數(shù)使用
let minuteInterval = 5
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
    // render the tick mark every 5 minutes (0, 5, 10, 15 ... 45, 50, 55)
}
//閉區(qū)間也同樣適用,使用 stride(from:through:by:) 即可

9、 .first(where: ...) 是一個用于在集合中查找滿足指定條件的第一個元素的方法。它的使用方式如下:
便利的循環(huán)條件篩選 使用 is 來判斷

eg:1
let numbers = [1, 2, 3, 4, 5]

if let firstEvenNumber = numbers.first(where: { $0 % 2 == 0 }) {
    print("The first even number is \(firstEvenNumber)")
} else {
    print("No even number found")
}


eg:2
 if let targetViewController = UINavigationController.jk_topNav().viewControllers.first(where: { $0 is JKHealthReportController}) {
            UINavigationController.jk_topNav().popToViewController(targetViewController, animated: false)
            UINavigationController.jk_topNav().pushViewController(JKHealthReportFilesController(title: "原始資料"), animated: true)
 }

??在 Swift 閉包中,$0 是一種特殊的語法,用于表示閉包的第一個參數(shù)。它可以用于簡化閉包的書寫。


10、Switch

let anotherCharacter: Character = "a"
let message :String
 switch anotherCharacter {
case "a":
    "The first letter of the Latin alphabet"
case "z":
    "The last letter of the Latin alphabet"
default:
    "Some other character"
}
// ??沒有隱式貫穿,不需要break


// 匹配多個值可以用逗號分隔
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a", "A":
    print("The letter A")
default:
    print("Not the letter A")
}

// 可以區(qū)間條件匹配
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
var naturalCount: String
switch approximateCount {
case 12..<100:
    naturalCount = "dozens of"
case 100..<1000:
    naturalCount = "hundreds of"
default:
    naturalCount = "many"
}


// switch 情況可以將匹配到的值臨時綁定為一個常量或者變量
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
    print("on the x-axis with an x value of \(x)")
case (0, let y):
    print("on the y-axis with a y value of \(y)")
case let (x, y):
    print("somewhere else at (\(x), \(y))")
}

11、類型檢查
is :來檢查一個實例是否屬于一個特定的子類
as? 或 as! :向下類型轉換至其子類類型

舉個例子(Movie和Song同時繼承父類MediaItem,library是MediaItem的數(shù)組)

//前提
let library = [
    Movie(name: "Casablanca", director: "Michael Curtiz"),
    Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
    Movie(name: "Citizen Kane", director: "Orson Welles"),
    Song(name: "The One And Only", artist: "Chesney Hawkes"),
    Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
]
// "library" 的類型被推斷為[MediaItem]

// is使用如下
for item in library {
    if item is Movie {
        movieCount += 1
    } else if item is Song {
        songCount += 1
    }
}

// as? 或 as!使用如下
for item in library {
    if let movie = item as? Movie {
        print("Movie: '\(movie.name)', dir. \(movie.director)")
    } else if let song = item as? Song {
        print("Song: '\(song.name)', by \(song.artist)")
    }
}

Any 和 AnyObject 的類型轉換

  • AnyObject 可以表示任何類類型的實例。
  • Any 可以表示任何類型,包括函數(shù)類型。

as 和 as? as! swift中區(qū)別如下:

在 Swift 中,as 關鍵字是用于轉換類型的。它有如下三種形式:
as?:可選轉換,將一個實例轉換為一個可選的目標類型。如果實例可以轉換為該類型,則返回可選值,否則返回 nil。
as!:強制轉換,將一個實例強制轉換為目標類型。如果實例不能轉換為該類型,則會在運行時引發(fā)異常。
as :條件轉換,將一個實例轉換為目標類型。如果實例不能轉換為該類型,則返回 nil。
因此,這三種形式的 as 在 Swift 中有不同的含義和使用方法。一般來說,當您確定轉換一定可以成功時,使用 as! 進行強制轉換會更加方便;而當您無法確定轉換是否可以成功時,使用 as? 進行可選轉換會更加安全。而 as 則需要根據(jù)實際情況進行選擇,如果您希望在失敗時返回 nil,那么使用 as,否則可以使用 as! 或者 try! 等方式。
??需要注意的是,在使用 as 進行轉換時,目標類型必須是可選類型或允許為空的類型(比如 Optional,Any 和 AnyObject),否則編譯器會報錯。

進一步說明as 和 as?區(qū)別
在 Swift 中,as 和 as? 都是用于類型轉換的關鍵字,但它們在轉換失敗時的處理方式不同。
在進行類型轉換時,如果轉換目標類型不能完全匹配原始類型,那么就需要進行類型轉換。
當使用 as 進行類型轉換時,如果無法將原始類型轉換為目標類型,則會返回一個可選類型,其值為 nil,表示類型轉換失敗。
而當使用 as? 進行類型轉換時,如果無法將原始類型轉換為目標類型,則會返回 nil,而不是一個可選類型。這意味著,在使用 as? 進行類型轉換時,您需要在代碼中明確地處理類型轉換失敗的情況;而在使用 as 進行類型轉換時,則可以使用可選綁定或空合運算符等機制來處理轉換失敗的情況。

let value: Any = 42

// 使用 as? 進行類型轉換
if let intValue = value as? Int {
    print("The integer value is \(intValue)")
} else {
    print("Cannot convert to integer")
}

// 使用 as 進行類型轉換
let intValue = value as Int?
if intValue != nil {
    print("The integer value is \(intValue!)")
} else {
    print("Cannot convert tinteger")
}
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容