加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:34:49 所属栏目:百科 来源:网络整理
导读:##传统写法 曾经我们这样初始化一个常量 let redView: UIView = { let view = UIView() view.backgroundColor = .red view.frame = CGRect(x: 100,y: 100,width: 100,height: 100) return view }() OC中也有类似的写法.在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读