Swift编程

Swift学习记录-有趣的操作

2019-07-01  本文已影响51人  JollyJerry

这一个文章不介绍swift的基础知识,只是记录从OC向Swift中转换时关注的点和觉得有意思的东西!

1、加载图片资源

//    加载Assets.xcassets中图片资源
        imageView.image = UIImage(named: "")
        imageView.image = UIImage.init(named: "")
//   加载项目文件中其他图片资源        
        imageView.image = UIImage.init(imageLiteralResourceName: "")
//   还有一中写法是
       #imageLiteral(resourceName: "")
      或者 直接写 (Image Literal)效果相同

2、高阶函数

1、sort -> 对数组排序函数

1. sorted
常用来对数组进行排序.
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、简写方式:
let sortTwoArry = intArry.sorted { (a: Int, b: Int) in
    return a < b
}

3、省略参数类型
let sortThreeArry = intArry.sorted { (a,b) in
    return a < b
}

4、省略虚拟参数
let sortFourArry = intArry.sorted {
    return $0 < $1
}

5、省略返回方式
let sortFiveArry = intArry.sorted {
    $0 < $1
}

//  [1, 2, 3, 4, 5, 7, 9, 34, 45]
ps: 最简单方式
 let sortSixArry = intArry.sorted(by: <)

3、记录一下如下操作

这个是在其他地方看到的操作,觉得比较容易理解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、字符串分割,转化成数组

//  字符串转换成数组的方法
//   需求: 如下字符串,按照 , 拆分并转换成数组!
let testStr : String = "123456789,abcdefghigk,lmnopqr,stuvwxyz"

//  字符串分割  ---   也算是一种转数组的方式
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"]

// 方法三 : 方法二的简便写法
var araabb = tempStrArry.compactMap {$0}
//  ["123456789", "abcdefghigk", "lmnopqr", "stuvwxyz"]

// 方法四
var arraacc = testStr.components(separatedBy: ",")
// ["123456789", "abcdefghigk", "lmnopqr", "stuvwxyz"]

未完,待续……

上一篇 下一篇

猜你喜欢

热点阅读