0

I'm new to Swift and don't much experience programming to begin with, and I have written this code with the intention of converting a binary input into a base 10 output. Can anyone tell me where the breakdown is and explain how to do it correctly? Much appreciated.

func toBaseTen(baseTwo: String) -> String{
    let reversed = String(baseTwo.characters.reverse()) //cast to String or else returns a ReverseCollection
    let toArray = reversed.characters.map { String($0) }
    var finalString = [String]()
    for element in toArray {
        let exponent = Double(toArray.indexOf(element)!)
        let elementToBeAdded = { String(pow(Double(element)!, exponent)) }
        if element == "1" {
            finalString.append(elementToBeAdded())
        }
    }
    finalString.reduce("", combine: +)
    return String(finalString)

}

  • 3
    Refer this post http://stackoverflow.com/questions/26790660/how-to-convert-a-binary-to-decimal-in-swift – Twitter khuong291 Sep 07 '16 at 03:57
  • thanks for the reference, I should clarify my question. I know there is an easier way to do this (i.e. the way you just posted). Why does my code not accomplish what I want it to? I'm doing this more as a programming exercise than a Swift exercise if that makes sense. Trying to learn. – yeezusplusplus Sep 07 '16 at 04:30
  • @yeezusplusplus: In that case please show your input data, the actual output, and the expected output. – Martin R Sep 07 '16 at 06:55

0 Answers0