swift 中如何使用selector

来源:互联网 发布:美工学徒招聘 编辑:程序博客网 时间:2024/06/01 09:23

selector是oc和swift都有的结构体.selector可以帮助我们实现对方法的动态调用可以很方便的处理一些特殊需求.swift中的结构体可以像oc中那样使用,但是也有些不同.本文就swift中selector的操作做了个小结.

1.Selector结构

public struct Selector : ExpressibleByStringLiteral {    /// Create a selector from a string.    public init(_ str: String)    /// Create an instance initialized to `value`.    public init(unicodeScalarLiteral value: String)    /// Construct a selector from `value`.    public init(extendedGraphemeClusterLiteral value: String)    /// Create an instance initialized to `value`.    public init(stringLiteral value: String)}extension Selector : Equatable, Hashable {    /// The hash value.    ///    /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`    ///    /// - Note: the hash value is not guaranteed to be stable across    ///   different invocations of the same program.  Do not persist the    ///   hash value across program runs.    public var hashValue: Int { get }}extension Selector : CustomStringConvertible {    /// A textual representation of `self`.    public var description: String { get }}extension Selector : CustomReflectable {    /// Returns a mirror that reflects `self`.    public var customMirror: Mirror { get }}

从selector的定义可以看出selector是一个结构体.它实现了字面量的协议,可以使用字符串直接定义selector.同时实现了Equatable和hash协议,这样可以很方便的进行selector对比.对反射协议的实现意味着未来可以对selector有更多场景的使用.

2.Selector的初始化方法有如下几种:

(1).直接加#selector初始化

let action:Selector = #selector(ViewController.test)

(2).getter和setter方法.

下面的例子获取person类的set和get的selector.前面需要添加getter和setter和label

...class Person: NSObject {    var firstName: String    dynamic let lastName: String    var fullName: String {        return "\(firstName) \(lastName)"    }    init(firstName: String, lastName: String) {        self.firstName = firstName        self.lastName = lastName    }}...  let firstNameGetter = #selector(getter: Person.firstName)  let firstNameSetter = #selector(setter: Person.firstName)

(3).从字符串获取selector

//第一种方式   let string: NSString = "test"   let selector = #selector(NSString.lowercased(with:))//第二种方式.注意带参数的需要加with变成oc的写法    let name = "log2WithParam1:"    let testSelector = NSSelectorFromString(name)    func log2(param1:String) {        print(param1)    }//第三种方式.因为selector实现了字面量协议,因此可以直接声明 let sel3:Selector = "log2WithParam1:" self.performSelector(inBackground: sel3, with: "12")

3.类型歧义处理

func commonFunc() {}func commonFunc(input: Int) -> Int {    return input}let method = #selector(commonFunc) // 编译错误,`commonFunc` 有歧义//添加类型说明       let method1 = #selector(commonFunc as ()->())let method2 = #selector(commonFunc as (Int)->Int)//错误用法//let method = #selector(commonFunc) // 编译错误,`commonFunc` 有歧义//正确用法:添加类型说明       let method1 = #selector(commonFunc as ()->())let method2 = #selector(commonFunc as (Int)->Int)

参考资料

苹果官网链接

https://github.com/apple/swift-evolution/blob/master/proposals/0064-property-selectors.md

http://swifter.tips/selector/

0 0
原创粉丝点击