Swift 中 String(describing: self) 和 type(of: self) 探究

459 阅读1分钟

总结:

#functionString(describing: self)type(of: self)
方法testFunc()SwiftExpand.SettingsServiceSettingsService
类方法testFunc()SettingsServiceSettingsService.Type
属性isNotificationsEnabledSwiftExpand.SettingsServiceSettingsService
类属性isNotificationsEnabledSettingsServiceSettingsService.Type

备注:SwiftExpand为命名空间,SettingsService 为类,

public extension UserDefaults{
    
    subscript<T>(key: String) -> T? {
        get {
            return value(forKey: key) as? T
        }
        set {
            set(newValue, forKey: key)
        }
    }
}

public class SettingsService {
    
    public required init() {
        
    }
    
    public var isNotificationsEnabled: Bool {
        get {
            let isEnabled = UserDefaults.standard.value(forKey: #function) as? Bool
            return isEnabled ?? true
        }
        set {
            DDLog(#function, String(describing: self), type(of: self))
            UserDefaults.standard.setValue(newValue, forKey: #function)
        }
    }
   
    public static var isNotificationsEnabled: Bool {
        get {
            let isEnabled = UserDefaults.standard.value(forKey: #function) as? Bool
            return isEnabled ?? true
        }
        set {
            DDLog(#function, String(describing: self), type(of: self))
            UserDefaults.standard.setValue(newValue, forKey: #function)
        }
    }

    public func testFunc() {
        DDLog(#function, String(describing: self), type(of: self))
    }
    
    public static func testFunc() {
        DDLog(#function, String(describing: self), type(of: self))
    }
}
🌰🌰:
        let service = SettingsService()
        service.testFunc()
        service.isNotificationsEnabled = false

        SettingsService.isNotificationsEnabled = false
        SettingsService.testFunc()

2020-12-30 01:28:23.586 UserDefaults+Helper.swift.testFunc()[line 158]: testFunc(), SwiftExpand.SettingsService, SettingsService
2020-12-30 01:28:23.586 UserDefaults+Helper.swift.testFunc()[line 162]: testFunc(), SettingsService, SettingsService.Type
2020-12-30 01:28:23.586 UserDefaults+Helper.swift.isNotificationsEnabled[line 122]: isNotificationsEnabled, SwiftExpand.SettingsService, SettingsService
2020-12-30 01:28:23.586 UserDefaults+Helper.swift.isNotificationsEnabled[line 143]: isNotificationsEnabled, SettingsService, SettingsService.Type