2016-11-18 121 views
0

我试图寻找一些关于像golang结构标记属性标签,我没有发现任何关于在SWIFT我们至少有别的选择吗?斯威夫特3属性标签

Golang STRUCT:

struct { 
microsec uint64 "field 1" 
serverIP6 uint64 "field 2" 
process string "field 3" 
} 

回答

1

有在夫特容易获得没有这样的属性的标签;对于关于雨燕提供声明和类型属性的详细信息,请参阅:

如果我们专注于运行时反省,但是,你可以使用Mirror structure来打印你的类型的属性名称,如下:

struct Foo { 
    let microsec: UInt64 //"field 1" 
    let serverIP6: UInt64 // "field 2" 
    let process: String // "field 3" 
    init(_ microsec: UInt64, _ serverIP6: UInt64, _ process: String) { 
     self.microsec = microsec 
     self.serverIP6 = serverIP6 
     self.process = process 
    } 
} 

let foo = Foo(100, 999, "foo") 

Mirror(reflecting: foo).children.forEach { print($0.0 ?? "no field name") } 
/* microsec 
    serverIP6 
    process */ 

如果你所提到的属性标签的唯一目的是利用Mirror运行时自省,那么你就可以实现自己的自定义Mirror你的类型,通过符合CustomReflectable protocol,适合你的内省的目的。在这个自定义实现中,你可以用你自己的字段替换默认的属性名称。例如: -

struct Foo { 
    let microsec: UInt64 //"field 1" 
    let serverIP6: UInt64 // "field 2" 
    let process: String // "field 3" 
    init(_ microsec: UInt64, _ serverIP6: UInt64, _ process: String) { 
     self.microsec = microsec 
     self.serverIP6 = serverIP6 
     self.process = process 
    } 
} 

extension Foo : CustomReflectable { 
    var customMirror: Mirror { 
     return Mirror(self, children: [ 
      "field 1" : "\(microsec)", 
      "field 2" : "\(serverIP6)", 
      "field 3" : process 
     ]) 
    } 
} 

let foo = Foo(100, 999, "foo") 

Mirror(reflecting: foo).children 
    .forEach { print($0.0 ?? "no field name", $0.1) } 
/* field 1 100 
    field 2 999 
    field 3 foo */ 
+0

感谢您的回答,dfri。 – eduardo

+0

@eduardo乐意帮忙! – dfri