一,创建闭包属性,赋值并且执行,使其弱引用:
var flag: Bool = false; //定义 var operate: ((String) -> String)? ; // override func viewDidLoad() { super.viewDidLoad() //赋值 self.operate = { [weak self] (text: String) -> String in return "\(text) + \(self!.flag)"; }; //执行 let op = operate!("this is block"); print(op); }
一般应用于:
var operate_q: (() -> Void)?;
self.dismiss(animated: true, completion: self.operate_q);
二,反向传递bolck,外部处理内部事物,通过代理传递出block:
typealias RecordListPlayButtonSelectedHandle = (_ isChange: inout Bool) -> Void; protocol SKRecordListCellProtocol: NSObjectProtocol { ///点击播放或暂停 func recordListCellPlayAndPauseOperate(recordListCell:SKRecordListCell,playAndPauseButton: UIButton,selectedHandle: RecordListPlayButtonSelectedHandle) -> Void; } /// ///播放,暂停 @objc func playAndPauseEvent(_ sender: UIButton) -> Void { if delegate != nil { let selectedHandle: RecordListPlayButtonSelectedHandle = { (isChange: inout Bool) -> Void in print(isChange); if isChange == true { sender.isSelected = !sender.isSelected; } }; delegate?.recordListCellPlayAndPauseOperate(recordListCell: self, playAndPauseButton: sender, selectedHandle: selectedHandle); } } ///实现 extension SKHomePageController: SKRecordListCellProtocol { ///播放,暂停代理 func recordListCellPlayAndPauseOperate(recordListCell: SKRecordListCell, playAndPauseButton: UIButton, selectedHandle: (inout Bool) -> Void) { print("recordListCellPlayAndPauseOperate"); var isChange = true; selectedHandle(&isChange); } }
三,swift数组转换成c语言数组指针:
var bytes: [Float32] = [39.0, 77.0, 111.0, 111.0, 102.0, 33.0, 39.0, 0.0]; let float32Pointer = UnsafeMutablePointer<Float32>.allocate(capacity: 8); float32Pointer.initialize(from: &bytes, count: 8); print("float32Pointer - - - \(float32Pointer)");
四,定义OC和swift不同的类名:
// OC用MLKText,swift用Text // NS_SWIFT_NAME(Text) @interface MLKText : NSObject // //
五,Swift遍历数组。
// // let resultModels: [SkyPredictorResultModel] = predictions.map { prediction in //prediction为其中的某一个元素 } // //
Swift遍历数组,获取数组中的前两个:
// // let resultModels: [SkyPredictorResultModel] = predictions.prefix(2).map { prediction in //prediction为其中的某一个元素 } // //