Is there a way to combine switch and contains?
This works for your case
let photos: Set = ["jpg", "png", "tiff"]
let videos: Set = ["mp4", "mov", "mkv"]
let audios: Set = ["mp3", "wav", "wma"]
enum FileType {
case photo, video, audio, unknown
}
func getType(of file: String) -> FileType {
switch true {
case photos.contains(file):
return .photo
case videos.contains(file):
return .video
case audios.contains(file):
return .audio
default:
return .unknown
}
}
print(getType(of: "mp4"))
video
You can switch on true
and then use each case as the conditional when you have multiple conditions.
You can add an overload to the pattern-matching operator ~=
:
func ~= <T> (pattern: Set<T>, value: T) -> Bool {
return pattern.contains(value)
}
func getType(of file: String) -> FileType {
switch file {
case photos: return .photo
case videos: return .video
case audios: return .audio
default: return .unknown
}
}
I think your whole problem is the fact that you are trying to maintain 3 independent sets for every type instead of connecting them directly to a given file type:
enum FileType: String {
case photo, video, audio, unknown
}
let extensions: [FileType: Set<String>] = [
.photo: ["jpg", "png", "tiff"],
.video: ["mp4", "mov", "mkv"],
.audio: ["mp3", "wav", "wma"]
]
func getType(of file: String) -> FileType {
return extensions.first { $0.value.contains(file) }?.key ?? .unknown
}