I'm using a third-party library that has an enum class defining some Media Device Types. I also have an API that can provide the Media Device Type to the Swift code as a string. I need to somehow get the Media Device Type from that string, so that I can pass it to another method.
Third-Party Enum
@objc public enum MediaDeviceType: Int, CustomStringConvertible {
case audioBluetooth
case audioWiredHeadset
case audioBuiltInSpeaker
case audioHandset
case videoFrontCamera
case videoBackCamera
case other
public var description: String {
switch self {
case .audioBluetooth:
return "audioBluetooth"
case .audioWiredHeadset:
return "audioWiredHeadset"
case .audioBuiltInSpeaker:
return "audioBuiltInSpeaker"
case .audioHandset:
return "audioHandset"
case .videoFrontCamera:
return "videoFrontCamera"
case .videoBackCamera:
return "videoBackCamera"
case .other:
return "other"
}
}
}
Things I've Tried:
As you can see, the .rawValue is an Int which means that I can't access the value using the initialiser for the enum:
let stringType = "audioBluetooth"
let type = MediaDeviceType(rawValue: stringType)
This gives me the error:
Cannot convert value of type 'String' to expected argument type 'Int'
I thought that maybe I could switch the stringType and return the correct media device type, but it seems that it doesn't actually work as expected when passing to the next method along.
private func getMediaTypeStringToEnum(type: String) -> MediaDeviceType? {
switch (type) {
case "audioBluetooth":
return .audioBluetooth
case "audioWiredHeadset":
return .audioWiredHeadset
case "audioBuiltInSpeaker":
return .audioBuiltInSpeaker
case "audioHandset":
return .audioHandset
case "videoFrontCamera":
return .videoFrontCamera
case "videoBackCamera":
return .videoBackCamera
case "other":
return .other
default:
return nil
}
}
The next method takes two parameters, a String, and an optional MediaDeviceType. If the second parameter doesn't match, the method switches the init method. Documentation.
My basic implementation:
let stringType = "audioBluetooth"
let label = "Media Device Label"
let hopefullyEnumType = getMediaTypeStringToEnum(stringType)
let mediaDevice = MediaDevice(label, hopefullyEnumType)
I'm very new to Swift, so maybe there's something obvious I'm missing here?