swift 弱化函数可帮助您将实例弱绑定到静态方法引用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 弱化函数可帮助您将实例弱绑定到静态方法引用相关的知识,希望对你有一定的参考价值。

// these functions take a swift class's statically referenced method and the instance those methods
// should apply to, and returns a function that weakly captures the instance so that you don't have
// to worry about memory retain cycles if you want to directly use an instance method as a handler
// for some object, like NSNotificationCenter.
//
// For more information, see this post:
// http://www.klundberg.com/blog/capturing-objects-weakly-in-instance-method-references-in-swift/

func weakify <T: AnyObject, U>(owner: T, f: T->U->()) -> U -> () {
    return { [weak owner] obj in
        if let this = owner {
            f(this)(obj)
        }
    }
}

func weakify <T: AnyObject>(owner: T, f: T->()->()) -> () -> () {
    return { [weak owner] in
        if let this = owner {
            f(this)()
        }
    }
}

func weakify <T: AnyObject, U>(owner: T, f: T->()->U) -> () -> U? {
    return { [weak owner] in
        if let this = owner {
            return f(this)()
        } else {
            return nil
        }
    }
}

func weakify <T: AnyObject, U, V>(owner: T, f: T->U?->()) -> V -> () {
    return { [weak owner] obj in
        if let this = owner {
            f(this)(obj as? U)
        }
    }
}

func weakify <T: AnyObject, U, V>(owner: T, f: T->U->V) -> U -> V? {
    return { [weak owner] obj in
        if let this = owner {
            return f(this)(obj)
        } else {
            return nil
        }
    }
}

func weakify <T: AnyObject, U>(owner: T, f: T->()->()) -> U -> () {
    return { [weak owner] _ in
        if let this = owner {
            f(this)()
        }
    }
}

以上是关于swift 弱化函数可帮助您将实例弱绑定到静态方法引用的主要内容,如果未能解决你的问题,请参考以下文章

为啥方法局部静态变量绑定到类而不是实例?

静态绑定与动态绑定

Swift:可以在可选绑定期间释放弱引用吗?

特性和静态方法

Swift 协议中的弱属性只能是类或类绑定协议类型

Swift如何实现通用类型的弱引用数组(下)