如何将 Struct 类型传递给 func 并返回该 Struct 的列表

Car*_*arl 4 generics struct swift

我将如何定义一个函数以采用 Struct 类型并返回它们的数组?

我不想为各种类型的 Struct 重复以下函数,而是定义一个函数,该函数可以接受定义要使用的 Struct 类型的参数。我已经看过关于简单类型和类的 Swift 泛型文档,但是我在将它应用于 Structs 时遇到了麻烦。

func getArray() -> [Thing]? {
    var things = [Thing]()
    let count = … some function …
    if count > 0 {
        for 0..<count {
            let dict = … some other function …
            things.append(Thing(representation:dict))
        }
        return things
    }
    return nil
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*all 6

关键是定义一个通用初始化器,编译器知道它可用于所有可能的结构类型。这是一个最小的例子:

protocol DictionaryInitializable {
    init(representation:[String:Any])
}

func getArray<T:DictionaryInitializable>(ofType type:T.Type)->[T] {
    let dictionary:[String:Any] = ["name" : "Hello World", "amount": 42]
    return [T](repeating: T(representation: dictionary), count: 3)
}

struct Test : DictionaryInitializable {
    let name:String
    init(representation: [String : Any]) {
        self.name = representation["name"] as? String ?? "Default Name"
    }
}

struct AnotherTest : DictionaryInitializable {
    let amount:Int
    init(representation: [String : Any]) {
        amount = representation["amount"] as? Int ?? 0
    }
}

var result = getArray(ofType:Test.self)
print(result) // prints "[Test(name: "Hello World"), Test(name: "Hello World"), Test(name: "Hello World")]"

let anotherResult = getArray(ofType:AnotherTest.self)
print(anotherResult) // prints "[AnotherTest(amount: 42), AnotherTest(amount: 42), AnotherTest(amount: 42)]"
Run Code Online (Sandbox Code Playgroud)