Hi,
I'd like to know how to handle errors when dealing with non-existing keys in a dictionary.
In the example below I have a function called complementOfDNA
, where I've placed a check if nil, throw
(EDITED) but it's obviously wrong, as I get Value of optional type 'String?' must be unwrapped to a value of type 'String'
. So, I'd like to learn how to handle errors in this context, if someone can point me in the right direction? I apologise but I did check Error Handling — The Swift Programming Language (Swift 5.7)
struct Nucleotide {
var RNATranscription = [
"G": "C",
"C": "G",
"T": "A",
"A": "U"
]
var DNAStrand: String
enum TranscriptionError: Error {
case invalidNucleotide(message: String)
}
init (_ DNAStrand: String) {
self.DNAStrand = DNAStrand
}
func complementOfDNA () throws -> [String] {
let split = self.splitter(self.DNAStrand)
var transcribed: [String] = []
for char in split {
let x = self.RNATranscription[char]
if x != nil {
transcribed.append(x)
} else {
throw TranscriptionError.invalidNucleotide(message: "\(char) is not a valid Nucleotide")
}
}
return transcribed
}
func splitter (_ text: String) -> [String] {
let arr = text.map {
String($0)
}
return arr
}
}