美文网首页程序员ios最佳实践
Swift最佳实践 3个符号让代码干净又整洁

Swift最佳实践 3个符号让代码干净又整洁

作者: 陈言强 | 来源:发表于2020-06-16 15:11 被阅读0次

自定义了三个运算符号 => =>> ==?,方便使用

import Foundation

precedencegroup RunPrecedenc {
    associativity: left // 代表没有结合性
    higherThan: BitwiseShiftPrecedence
    assignment: false
}

infix operator =>: RunPrecedenc

// 将入参 o 作为作用域执行闭包,并返回修饰后的入参
public func => <T: Any>(_ o: T, run: (_ v: T) -> Void) -> T {
    run(o)
    return o
}


precedencegroup ApplyPrecedenc {
    associativity: left // 代表没有结合性
    higherThan: RunPrecedenc
    assignment: false
}

infix operator =>>: ApplyPrecedenc

// 将入参 o 作为作用域执行闭包,无返回
public func =>> <T: Any>(_ o: T, run: (_ v: T) -> Void) {
    run(o)
}


precedencegroup RunNotNilPrecedenc {
    associativity: left // 代表没有结合性
    higherThan: BitwiseShiftPrecedence
    assignment: true
}

infix operator =>?: RunNotNilPrecedenc

// 将入参 o 作为作用域执行闭包,在入参非空的情况下执行
public func =>? <T: Any>(_ o: T?, run: (_ v: T) -> Void){
    if o != nil { run(o!) }
}

使用方法 以后变量的使用 修饰无需再使用临时变量接收

    /// 有返回值
    lazy var _centerText = UILabel() => { it in
        it.font = UIFont.systemFont(ofSize: 16)
        it.textColor = color_white_text
        it.backgroundColor = .red
        it.text = "文字居中 左偏移 50"
    }

//无返回值
 UILabel() =>> { it in
        it.font = UIFont.systemFont(ofSize: 16)
        it.textColor = color_white_text
        it.backgroundColor = .red
        it.text = "文字居中 左偏移 50"
    }

  let lab :  UILabel? = nil
  // lab 非空执行闭包
  lab =>? { it in
        it.font = UIFont.systemFont(ofSize: 16)
        it.textColor = color_white_text
        it.backgroundColor = .red
        it.text = "文字居中 左偏移 50"
    }

相关文章

网友评论

    本文标题:Swift最佳实践 3个符号让代码干净又整洁

    本文链接:https://www.haomeiwen.com/subject/ytcrxktx.html