I have an array of enums where each enum either contains an image or video. I would like to loop through the array and get the values inside each enum. If the enum contains an image I would like get that value and if it contains a video then get that value.
So how do I loop through an array if enums?
This is my code:
import UIKit
import AVFoundation
enum ContentSource {
case image(UIImage)
case video(AVPlayer)
}
var post : [ContentSource] = []
CodePudding user response:
You have to have a switch
to figure out what type it is in the loop.
var posts : [ContentSource] = []
for post in posts {
switch post {
case .image(let uIImage):
print("UIImage")
case .video(let aVPlayer):
print("UIImage")
}
}
CodePudding user response:
you could try something like this:
enum ContentSource: Hashable {
case image(UIImage)
case video(AVPlayer)
}
struct ContentView: View {
@State var posts : [ContentSource] = []
var body: some View {
List(posts, id: \.self) { item in
switch(item) {
case .image(let img):
Text(img.description) // show image
case .video(let avPlayer):
Text(avPlayer.description) // play video
}
}
.onAppear {
let img = UIImage(systemName: "globe")!
let av = AVPlayer()
posts = [.image(img), .video(av)]
}
}
}
CodePudding user response:
Can you try this , you can get the associated values and do as you wish with them
enum ContentSource {
case image(UIImage)
case video(AVPlayer)
}
var post :[ContentSource] = []
let testContent = ContentSource.video(AVPlayer())
switch testContent {
case .image(let img):
print("i got img")
case .video(let video):
print("i got video")
}