Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to combine switch and contains?

Let's assume that I have three sets containing extensions:

let photos: Set = ["jpg", "png", "tiff"]
let videos: Set = ["mp4", "mov", "mkv"]
let audios: Set = ["mp3", "wav", "wma"]

and a simple enum as:

enum FileType {
    case photo, video, audio, unknown
}

Now what I want to do is to implement a function that returns FileType option based on what is the passed string to it and which set contains it:

func getType(of file: String) -> FileType {
    if photos.contains(file) { return .photo }
    if videos.contains(file) { return .video }
    if audios.contains(file) { return .audio }

    return .unknown
}

It should work as expected, but I wonder if there is an approach to transform the if statement to one switch case (even if it would change the logic a bit), especially when working with enums the switch statement(s) is a better choice to avoid errors.

If it is unachievable by using switch statement, I would also appreciate any elegant alternative(s).

like image 772
Ahmad F Avatar asked May 10 '18 10:05

Ahmad F


2 Answers

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.

like image 144
Scriptable Avatar answered Sep 21 '22 12:09

Scriptable


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
    }
}
like image 25
Code Different Avatar answered Sep 19 '22 12:09

Code Different