结构作为函数中的参数,带完成-Swift

结构作为函数中的参数,带完成-Swift,swift,parameter-passing,func,Swift,Parameter Passing,Func,我遇到麻烦了,有没有可能在完成函数中设置一个参数?具体来说,我有2个结构,我希望用户选择其中一个。我的代码是这样的: struct Photo: Decodable { ... } //Function func fetchPhotos(url: String, completion: @escaping ([Photo]?, Error?) -> ()) { ... } 基本上我想要的是那个而不是[照片]?在完成之前,我可以设置一个参数。这可能吗 谢谢大家! 创建一个协议,并在两个协议

我遇到麻烦了,有没有可能在完成函数中设置一个参数?具体来说,我有2个结构,我希望用户选择其中一个。我的代码是这样的:

struct Photo: Decodable {
...
}
//Function
func fetchPhotos(url: String, completion: @escaping ([Photo]?, Error?) -> ()) {
...
}
基本上我想要的是那个而不是[照片]?在完成之前,我可以设置一个参数。这可能吗


谢谢大家!

创建一个协议,并在两个协议上确认它,并将其作为参数传递,你不关心对象是什么类型的,你只需要知道如何使用它。这就是为什么在完成后,你只需转换它的类型。你需要检查下面的代码,我添加了Video struct作为你的第二个,因为你在这个问题中没有

protocol Switchable: Decodable {

}

struct Video: Switchable {

}
struct Photo: Switchable {

}
//Function
func fetchPhotos(url: String, completion: @escaping ([Switchable]?, Error?) -> ()) {
     completion([],nil)
}
//Check on the result after completion is called
let v: [Switchable] = [Video(), Video()]

if let photos = v as? [Photo] {
    print("its photos", photos)
}
if let videos = v as? [Video] {
    print("its videos ",videos)
}
此外,对于实现fetchPhotos,使用enum似乎更合适,因为在completion参数中,我们询问的是result或error

您可以实现如下内容:

enum CustomError: Error {
    case notFound
}

enum Result<T> {
    case success(T)
    case failure(CustomError)
}

protocol Switchable: Decodable { }
struct Video: Switchable { }
struct Photo: Switchable { }
称之为:

fetchPhotos(url: "...") { result in
    switch result {

    case .success(let photos):
        // in case of photos
        if let photos = photos as? [Photo] { /**/ }

        // in case of videos
        if let videos = photos as? [Video] { /**/ }

        // in case of mix of photos and videos, you should iterate through it and check each object
        photos.forEach({ photo in
            if let media = photo as? Photo {

            } else if let media = photo as? Video {

            }
        })

    case .failure(let error):
        print(error.localizedDescription)

    }
}

另一个结构是什么,您需要对参数做什么,请解释更多。感谢您的回复,我的结构将与照片相同,但命名为相册。因此,基本上我正在解析2个JSON文件,它们有不同的元素要解析,原因是我需要选择第一个或第二个结构来正确解析JSONTANK您的答案!让v:[可切换]=[视频,视频]不应该让v:[可切换]=[视频,照片]。那么,我应该在协议中加入什么呢?我不完全理解你想做什么,但如果你也这样做的话,它会起作用
fetchPhotos(url: "...") { result in
    switch result {

    case .success(let photos):
        // in case of photos
        if let photos = photos as? [Photo] { /**/ }

        // in case of videos
        if let videos = photos as? [Video] { /**/ }

        // in case of mix of photos and videos, you should iterate through it and check each object
        photos.forEach({ photo in
            if let media = photo as? Photo {

            } else if let media = photo as? Video {

            }
        })

    case .failure(let error):
        print(error.localizedDescription)

    }
}