整理 Swift 开发用到的一些小技巧

Selector
import UIKit

private extension Selector {
    static let open = #selector(TestViewController.open(sender:))
}

class TestViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let openBtn : UIButton = UIButton()
        openBtn.addTarget(self, action: .open, for: .touchUpInside)
        view.addSubview(openBtn)
    }

    @objc fileprivate func open(sender: UIButton) {
    }
}

Extension的方式去扩展Selector,在会使用到Selector的情况下,调用是极其优雅的。比如UIButtonActionNotification

UIView….

在写一个view的时候,通常是这样去写的,

let view : UIView = UIView()
view.backgroundColor = .red

但其实,还可以用另外一种写法:

let view : UIView = {
    let tempView : UIView = UIView()
    tempView.backgroundColor = .red
    return tempView
}()

这样写,其实可以很好的隔离代码,看起来也更加方便。
另外,Objective-C也有类似的写法。

UIView *view = ({
     UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
     tempView.backgroundColor = [UIColor yellowColor];
     tempView;
});
常量,还有一些什么鬼

SwiftStruct去定义一些常量等是比较方便的。比如UIFont.
在UI开发中,经常会用到一些字体。Objective-C中,比较常用的是用。但是Swift中是无法使用的,所以使用Struct去定义一些常用的UIFont,也是比较方便的,另外,在使用上也是更加优雅。

// 定义这样的一个结构体
struct Fonts {
    static let content : UIFont = UIFont.systemFont(ofSize: 14.0)
}
// 使用
titleLabel.font = Fonts.content

同样,也适用于UIColor,比如

// 定义这样的一个结构体
struct Colors {
    static let title : UIColor = UIColor(red: 190.0/255.0, green: 180.0/255.0, blue: 170.0/255.0, alpha: 1)
}
// 使用
label.textColor = Colors.title

对于UIFontUIColor,其实也可以使用 extension,对其进行扩展。在使用上,也更加原生优雅。比如UIColor

extension UIColor {
    static let title : UIColor = UIColor(red: 190.0/255.0, green: 180.0/255.0, blue: 170.0/255.0, alpha: 1)
}
label.textColor = .title
for-in

Objective-C中,写一个for循环,应该是——

for(int i = 0; i < 5; i++ ) {
}

但是在Swift中,写for循环大多数快速遍历的形式——for-in。其实,这个在Objective-C中,也是存在的。但是在Swift里面,则多了一些变化,在配合上 where关键字的使用,也是极大的方便。

let arr = [1,2,3]
// 第一种方式
for element in xxArr {
    print(element)
}
log:1
    2
    3
// 第二种方式,如需使用到 序号
for i in 0..<arr.count {
    print("\(i):\(arr[i])")
}
log:0:1
    1:2
    2:3

// 第三种方式
for (index, element) in arr.enumerated() {
    print("\(index):\(element)")
}
log:0:1
    1:2
    2:3

如果,配合上where的话,可以进行一些条件的判断等

for (index, element) in arr.enumerated() where index < 2 {
    print("\(index):\(element)")
}
log:0:1
    1:2
    原文作者:六叔
    原文地址: https://segmentfault.com/a/1190000008172468
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞