Reputation: 3
In the code below I was trying to make a loop that would go through my string and add the value of each character in the string to the total variable.
var stringSent = "babbbababa"
let charValues = ["a":1,"b":2]
var total = 0
for i in stringSent.characters{
switch i{
case "a":
total += charValues["a"]!
//adds 1 to total
case "b":
total += charValues[i]!
//throws error
default:
print("default was sent")
}
print(total)
}
Initially I was going to use a for loop like so to keep lines to the fewest which I would love to do if I can figure out how to get the variable "i" to correctly be used as a key to retreive the current characters value.
for i in stringSent.characters {
total += charValues[i]
}
Am I doing something wrong with my dictionary or is this method not possible? I havent found anything helpful from apple or google.
Upvotes: 0
Views: 501
Reputation: 73176
It seems you want to calculate the weighted sum of the characters in the String
instance stringSent
(given some known weights for each Character
). The problem in your own implementation is that you're trying to access the value of a key in your dictionary using a variable that differs from the type of the dictionariy's key (Character
is not the same as String
)
total += charValues[i]! // 'i' is a Character here
You could simplify your implementation and likewise avoid making use of the explicit unwrapping (!
) in several different ways, e.g. applying reduce
to the CharacterView
of stringSent
var stringSent = "babbbababa"
let charValues = ["a": 1, "b": 2]
let total = stringSent.characters.reduce(0) { $0 + (charValues[String($1)] ?? 0) }
// 16
(With respect to the original misunderstood version of this answer), another (slightly more wasteful) alternative could be to calculate the frequencies of each character in the String
instance stringSent
, whereafter the associated weight could be applied to each frequency to compute the total weighted sum.
var stringSent = "babbbababa"
let charValues = ["a": 1, "b": 2]
var freqs: [String: Int] = [:]
stringSent.characters.forEach { freqs[String($0)] = (freqs[String($0)] ?? 0) + 1 }
print(freqs) // ["b": 6, "a": 4]
let total = freqs.reduce(0) { (sum, kv) in
sum + (charValues[kv.key].map { kv.value*$0 } ?? 0) }
// 16
Upvotes: 1
Reputation: 534950
The problem is that characters
are Characters but the keys in your dictionary are Strings. So just convert:
let stringSent = "babbbababa"
let charValues = ["a":1,"b":2]
var total = 0
for i in stringSent.characters{
total += charValues[String(i)]!
}
Or, go the other way — specify that the keys in the dictionary should be Characters:
let stringSent = "babbbababa"
let charValues : [Character:Int] = ["a":1,"b":2]
var total = 0
for i in stringSent.characters{
total += charValues[i]!
}
Upvotes: 1