Bigfoot11 Bigfoot11 - 7 months ago 15
Swift Question

Changing return type to a decimal?

I am trying to convert the current values that I am dealing with to hundredths. Here is my code:

extension String {
var value: Int {
if let found = Array("abc".characters).indexOf(Character(lowercaseString)) {
return found + 1
}
return 0
}
var totalValue: Int {
var result = 0
for letter in self.characters {
result += String(letter).value
}
return result
}
}


So the letter a would = .01, the letter b would = .02, and the letter c would = .03

How would I modify my code so this can happen?

EDIT

This is the code I am using:

@IBAction func sum(sender: AnyObject) {
strValue.text = String(format: "%.2f", "$\(strInput.text!.value.description)")
}


I have no idea if this is the right way to do it but there it is

JAL JAL
Answer

Divide the return value of value by 100?

extension String {
    var value: Float {
        if let found = Array("abc".characters).indexOf(Character(lowercaseString)) {
            return (Float(found + 1) / 100)
        }
        return 0
    }
    var totalValue: Float {
        var result: Float = 0
        for letter in self.characters {
            result += Float(String(letter).value)
        }
        return result
    }
}

"a".value // 0.01
"b".value // 0.02
"c".value // 0.03
"abc".totalValue // 0.06

To show each value with three decimal places, use a format String:

String(format: "%.3f", "a".value) // "0.010"

or with two decimal places:

String(format: "%.2f", 0.1) // 0.10
Comments