发现一种NB的Swift初始化常量的方法

##传统写法 曾经我们这样初始化一个常量

let redView: UIView = {
        let view = UIView()
            view.backgroundColor = .red
            view.frame = CGRect(x: 100,y: 100,width: 100,height: 100)
            return view
        }()

OC中也有类似的写法.在Swift中,声明一个常量之后接着的闭包中进行初始化,而不是之后在 viewDidLoad 或其他类似的方法中进行设置,这种写法的确也很不错! 但是否认为直接在闭包中使用view这样的命名方式显得太low了. twitter有一篇推文流传甚广.

他参照了一个gist

仿照上面的写法,在闭包中使用$0,执行时传入一个用来初始化的UIView

使用$0

let greenView: UIView = {
            $0.backgroundColor = .green
            $0.frame = CGRect(x: 100,y: 200,height: 100)
            return $0
        }(UIView())
        self.view.addSubview(greenView)

在推文评论中有哥们推荐了一个日本小伙子封装的库,瞬间感觉好NB

Git地址

其实也没多少代码 直接复制代码就能用

import Foundation
import CoreGraphics

public protocol Then {}

extension Then where Self: Any {
    
    /// Makes it available to set properties with closures just after initializing and copying the value types.
    ///
    ///     let frame = CGRect().with {
    ///       $0.origin.x = 10
    ///       $0.size.width = 100
    ///     }
    public func with(_ block: (inout Self) -> Void) -> Self {
        var copy = self
        block(©)
        return copy
    }
    
    /// Makes it available to execute something with closures.
    ///
    ///     UserDefaults.standard.do {
    ///       $0.set("devxoul",forKey: "username")
    ///       $0.set("devxoul@gmail.com",forKey: "email")
    ///       $0.synchronize()
    ///     }
    public func `do`(_ block: (Self) -> Void) {
        block(self)
    }
    
}

extension Then where Self: AnyObject {
    
    /// Makes it available to set properties with closures just after initializing.
    ///
    ///     let label = UILabel().then {
    ///       $0.textAlignment = .Center
    ///       $0.textColor = UIColor.blackColor()
    ///       $0.text = "Hello,World!"
    ///     }
    public func then(_ block: (Self) -> Void) -> Self {
        block(self)
        return self
    }
    
}

extension NSObject: Then {}

extension CGPoint: Then {}
extension CGRect: Then {}
extension CGSize: Then {}
extension CGVector: Then {}

##NB写法 例如

let label = UILabel().then {
        $0.frame = CGRect(x: 100,y: 300,height: 100)
            $0.text = "测试"
            $0.backgroundColor = .purple
            $0.textAlignment = .center
            $0.font = UIFont.systemFont(ofSize: 19)
        }
        self.view.addSubview(label)

三种方法同样可以做到初始化一个常量 不是你认为哪种更加酷呢哈哈哈

欢迎打赏 点赞,收藏,关注博主 iOS技术交流群 482478166

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...