0
我試圖尋找一些關於像golang結構標記屬性標籤,我沒有發現任何關於在SWIFT我們至少有別的選擇嗎?斯威夫特3屬性標籤
Golang STRUCT:
struct {
microsec uint64 "field 1"
serverIP6 uint64 "field 2"
process string "field 3"
}
我試圖尋找一些關於像golang結構標記屬性標籤,我沒有發現任何關於在SWIFT我們至少有別的選擇嗎?斯威夫特3屬性標籤
Golang STRUCT:
struct {
microsec uint64 "field 1"
serverIP6 uint64 "field 2"
process string "field 3"
}
有在夫特容易獲得沒有這樣的屬性的標籤;對於關於雨燕提供聲明和類型屬性的詳細信息,請參閱:
如果我們專注於運行時反省,但是,你可以使用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 */
感謝您的回答,dfri。 – eduardo
@eduardo樂意幫忙! – dfri