首页 热点资讯 义务教育 高等教育 出国留学 考研考公
您的当前位置:首页正文

Swift编程中的小技巧

2024-12-20 来源:化拓教育网

Defer管理程序控制流

defer语句会推迟包含这个命令的代码执行,直到当前范围终止。也就是说,在defer语句中清理逻辑是可以替换的,而且只要离开相应的调用范围,这段命令就肯定就会被调用。这样可以减少冗余步骤,更重要的是增加安全性。

func deferExample() {
    defer {
        print("Leaving scope, time to cleanup!")
    }
    print("Performing some operation...")
}

deferExample()

// Prints:
// Performing some operation...
// Leaving scope, time to cleanup!

Swizzle_method实现

Swift不必像OC一样实现方法对调, 可以使用下列代码实现方法对调:

import UIKit
class AwesomeClass {
    dynamic func originalFunction() -> String {
        return "originalFunction"
    }  
    dynamic func swizzledFunction() -> String {
        return "swizzledFunction"
    }
}
let awesomeObject = AwesomeClass()
print(awesomeObject.originalFunction()) // prints: "originalFunction"
let aClass = AwesomeClass.self
let originalMethod = class_getInstanceMethod(aClass, "originalFunction")
let swizzledMethod = class_getInstanceMethod(aClass, "swizzledFunction")
method_exchangeImplementations(originalMethod, swizzledMethod)
print(awesomeObject.originalFunction())  // prints: "swizzledFunction"

创建全局Helper函数

import Foundation

/**
    Executes the closure on the main queue after a set amount of seconds.

    - parameter delay:   Delay in seconds
    - parameter closure: Code to execute after delay
*/
func delayOnMainQueue(delay: Double, closure: ()->()) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), closure)
}

/**
    Executes the closure on a background queue after a set amount of seconds.

    - parameter delay:   Delay in seconds
    - parameter closure: Code to execute after delay
*/
func delayOnBackgroundQueue(delay: Double, closure: ()->()) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), closure)
}

//封装后调用
delayOnBackgroundQueue(5) {
    showView()
}

//封装前调用
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)) {
    showView()
}
显示全文