這一個(gè)文章不介紹swift的基礎(chǔ)知識(shí),只是記錄從OC向Swift中轉(zhuǎn)換時(shí)關(guān)注的點(diǎn)和覺得有意思的東西!
1茴扁、加載圖片資源
// 加載Assets.xcassets中圖片資源
imageView.image = UIImage(named: "")
imageView.image = UIImage.init(named: "")
// 加載項(xiàng)目文件中其他圖片資源
imageView.image = UIImage.init(imageLiteralResourceName: "")
// 還有一中寫法是
#imageLiteral(resourceName: "")
或者 直接寫 (Image Literal)效果相同
2、高階函數(shù)
1火邓、sort -> 對(duì)數(shù)組排序函數(shù)
1. sorted
常用來對(duì)數(shù)組進(jìn)行排序.
let intArry = [4,5,7,9,1,45,3,2,34]
let sortArry = intArry.sorted { (a: Int, b: Int) -> Bool in
return a < b
}
2丹弱、簡(jiǎn)寫方式:
let sortTwoArry = intArry.sorted { (a: Int, b: Int) in
return a < b
}
3德撬、省略參數(shù)類型
let sortThreeArry = intArry.sorted { (a,b) in
return a < b
}
4、省略虛擬參數(shù)
let sortFourArry = intArry.sorted {
return $0 < $1
}
5躲胳、省略返回方式
let sortFiveArry = intArry.sorted {
$0 < $1
}
// [1, 2, 3, 4, 5, 7, 9, 34, 45]
ps: 最簡(jiǎn)單方式
let sortSixArry = intArry.sorted(by: <)
3蜓洪、記錄一下如下操作
這個(gè)是在其他地方看到的操作,覺得比較容易理解try-catch 和where的綜合使用坯苹!
enum ExceptionError: Error {
case httpCode(Int)
}
func throwError() throws {
throw ExceptionError.httpCode(500)
}
do {
try throwError()
} catch ExceptionError.httpCode(let httpCode) where httpCode >= 500 {
print("server error")
} catch {
print("other error")
}
4隆檀、字符串分割,轉(zhuǎn)化成數(shù)組
// 字符串轉(zhuǎn)換成數(shù)組的方法
// 需求: 如下字符串粹湃,按照 , 拆分并轉(zhuǎn)換成數(shù)組恐仑!
let testStr : String = "123456789,abcdefghigk,lmnopqr,stuvwxyz"
// 字符串分割 --- 也算是一種轉(zhuǎn)數(shù)組的方式
var tempStrArry : Array<Substring>! = testStr.split(separator: ",")
// ["123456789", "abcdefghigk", "lmnopqr", "stuvwxyz"] ---- 類型:Substring
print(tempStrArry!)
// 方法一 :
var araaaa = tempStrArry.map(String.init)
// ["123456789", "abcdefghigk", "lmnopqr", "stuvwxyz"]
// 方法二
var araab = tempStrArry.compactMap { (strArry) -> String? in
return "\(strArry)"
}
// ["123456789", "abcdefghigk", "lmnopqr", "stuvwxyz"]
// 方法三 : 方法二的簡(jiǎn)便寫法
var araabb = tempStrArry.compactMap {$0}
// ["123456789", "abcdefghigk", "lmnopqr", "stuvwxyz"]
// 方法四
var arraacc = testStr.components(separatedBy: ",")
// ["123456789", "abcdefghigk", "lmnopqr", "stuvwxyz"]