gpt4 book ai didi

swift - 面向协议(protocol)编程: General struct of type Any in Protocol + introspection valueForKey()

转载 作者:行者123 更新时间:2023-11-30 13:31:25 31 4
gpt4 key购买 nike

当为 Any 类型的结构设置协议(protocol)时,我希望可以将结构的类型设置为我想要的类型。以下代码是从我制作的 Playground 粘贴的:

import Foundation

// MyStruct does not conform to protocol StructProtocol
// With a general type for struct, like Any, AnyStruct or just Struct, this should be possible
struct MyStruct: StructProtocol {
var thisStruct: ThisStruct
var thatStruct: ThatStruct
}

struct ThisStruct {
var someString: String
}

struct ThatStruct {
var someOtherString: String
var andAnotherString: String
}

protocol StructProtocol {
// Should be able to put Any / AnyStruct / Struct here for a generic struct
var thisStruct: Any {get}
var thatStruct: Any {get}
}

extension StructProtocol {
func saySomething() {
let firstMirror = Mirror(reflecting: self.thisStruct)
let secondMirror = Mirror(reflecting: self.thatStruct)

for structVar in firstMirror.children {
print(self.thisStruct.valueForKey(structVar))
}

for structVar in secondMirror.children {
print(self.thatStruct.valueForKey(structVar))
}
}
}

var thisStruct = ThisStruct(someString: "Hi")
var thatStruct = ThatStruct(someOtherString: "Hello", andAnotherString: "Hola")

var myStruct = MyStruct(thisStruct: thisStruct, thatStruct: thatStruct)
myStuct.saySomething()

// Should output "Hi", "Hello" and "Hola"

目前,协议(protocol)没有可以引用的通用结构类型。必须将结构变量设置为与协议(protocol)完全相同的类型。也许我误解了这一点,并且有一种方法可以实现我正在寻找的东西,但到目前为止我还没有找到答案。

我认为在 Swift 中做到这一点会很棒,所以如果没有办法实现这一点,我会将其作为 Swift 项目中的功能请求发布,但首先我将由各位专家在 StackOverflow 中运行它。

所以问题是:这是否可以通过其他方式实现?

最佳答案

您可以使用多种协议(protocol)执行您所描述的操作。您所要求的问题是如何使用这些通用结构(如果它们不符合其他协议(protocol)或采用一些通用参数) - 您必须对它们进行强制转换,然后通用的全部要点你所要求的自然已经失去了。

所以,你可以这样做:

protocol InnerProtocol {
func printChildren()
}

protocol StructProtocol {
var inner1: InnerProtocol {get}
var inner2: InnerProtocol {get}
}


struct MyStruct : StructProtocol {
var inner1: InnerProtocol
var inner2: InnerProtocol
}

struct ThisStruct : InnerProtocol {
var someString: String

func printChildren() {
print(someString)
}
}

struct ThatStruct : InnerProtocol {
var someOtherString: String
var andAnotherString: String

func printChildren() {
print(someOtherString)
print(andAnotherString)
}
}

extension StructProtocol {

func saySomething() {
inner1.printChildren()
inner2.printChildren()
}
}


var thisStruct = ThisStruct(someString: "Hi")
var thatStruct = ThatStruct(someOtherString: "Hello", andAnotherString: "Hola")

var myStruct = MyStruct(inner1: thisStruct, inner2: thatStruct)
myStruct.saySomething()

关于swift - 面向协议(protocol)编程: General struct of type Any in Protocol + introspection valueForKey(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36543157/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com