栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

迅速列出课程属性

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

迅速列出课程属性

使用
Mirror

这是一个纯粹的Swift解决方案,但有一些限制:

protocol PropertyNames {    func propertyNames() -> [String]}extension PropertyNames{    func propertyNames() -> [String] {        return Mirror(reflecting: self).children.flatMap { $0.label }    }}class Person : PropertyNames {    var name = "Sansa Stark"    var awesome = true}Person().propertyNames() // ["name", "awesome"]

局限性:

  • 返回Objective-C对象的空数组
  • 将不返回计算的属性,即:

    var favoriteFood: String { return "Lemon Cake" }
  • 如果

    self
    是类的实例(相对于结构),则不会报告其超类的属性,即:

    class Person : PropertyNames {var name = "Bruce Wayne"

    }

    class Superhero : Person {
    var hasSuperpowers = true
    }

    Superhero().propertyNames() // [“hasSuperpowers”] — no “name”

您可以

superclassMirror()
根据所需的行为来解决此问题。

使用
class_copyPropertyList

如果使用的是Objective-C对象,则可以使用以下方法:

var count = UInt32()let classToInspect = NSURL.selflet properties : UnsafeMutablePointer <objc_property_t> = class_copyPropertyList(classToInspect, &count)var propertyNames = [String]()let intCount = Int(count)for var i = 0; i < intCount; i++ {    let property : objc_property_t = properties[i]    guard let propertyName = NSString(UTF8String: property_getName(property)) as? String else {        debugPrint("Couldn't unwrap property name for (property)")        break    }    propertyNames.append(propertyName)}free(properties)print(propertyNames)

到控制台的输出是否

classToInspect
NSURL

["pathComponents", "lastPathComponent", "pathExtension","URLByDeletingLastPathComponent", "URLByDeletingPathExtension","URLByStandardizingPath", "URLByResolvingSymlinksInPath","dataRepresentation", "absoluteString", "relativeString", "baseURL","absoluteURL", "scheme", "resourceSpecifier", "host", "port", "user","password", "path", "fragment", "parameterString", "query", "relativePath","hasDirectoryPath", "fileSystemRepresentation", "fileURL","standardizedURL", "filePathURL"]

这在操场上行不通。只需替换

NSURL
EachDayCell
(或重用与扩展相同的逻辑),它就可以工作。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/374384.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号