自包含的通用

我有以下协议:

public protocol ImagesContainer {
    associatedtype ImageName: RawRepresentable where ImageName.RawValue == String
    static var bundle: Bundle? { get }
}

用这样的实现

struct ImagesMain: ImagesContainer {
    public static var bundle: Bundle? { return .main }
    public enum ImageName: String {
        case loading, success, error
        case profile, address
    }
}

struct ImagesUser: ImagesContainer {
    public static var bundle: Bundle? { return .main }
    public enum ImageName: String {
        case profile, address, country
    }
}

所以通常我在模型结构中使用过

struct ViewModel {
    let icon: ImagesMain.ImageName
}

which is fine for one ImagesContainer. But I have one such container for each bundle and I would like to mix and match them when creating those ViewModels. For now they are always tied to one ImagesContainer. I would like to generalize that, so that I can specify any ImageName from any ImagesContainer.

就像是

struct ViewModel {
    let profileIcon<T: ImagesContainer>: (T, T.ImageName)
    let addressIcon<T: ImagesContainer>: (T, T.ImageName)

}

I can't put this on the struct itself, because there may be multiple properties with different ImagesContainers and so on. Is there a way to have a self-contained generic?

评论