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

Struct as parameter in function with Completion - Swift

麻烦了,有没有可能在Completion里面设置一个函数的参数?具体来说,我有 2 个结构,我希望用户 select 其中之一。我的代码是这样的:

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,似乎使用枚举更合适,因为在completion参数中我们要求"result OR 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 为:

func fetchPhotos(url: String, completion: @escaping (Result<[Switchable]>) -> Void) {
    // in case of error:
    let error: CustomError? = CustomError.notFound
    if let error = error {
        completion(.failure(error))
    }

    // in case of success - videos:
    completion(.success([Video(), Video()]))

    // in case of success - photos:
    completion(.success([Photo(), Photo()]))
}

称其为:

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)

    }
}