Search code examples
swiftdouble

Double Extension Swift


I am trying to create an iOS Swift extension in a playground to the Double type that implements a method titled add that receives a String and returns an optional Double (Double?).

Extend the Double type, using an extension, and add a method called add that takes a String as a parameter with no label and returns a Double?.

If the String parameter can be turned into a Double, return the String’s Double value plus the value of the Double on which add is being called. If the String cannot be turned into a Double, return nil.

For testing this code I need to use:

let value1: Double? = 3.5.add("1.2") //value should be 4.7

let value3: Double? = 1.5.add("words") //value should be nil
extension Double {
    func add(_ value: String) -> Double? {
        guard let someNum = Double?(self) else {
            return nil
        }
        return (someNum + value)
    }
}

https://i.sstatic.net/VLM2E.png


Solution

  • Looks like you got a little confused about what to unwrap in your guard statement and what needed to be turned from a String into a Double. In your current code, you try to turn self, which is already a Double into a Double? -- then, you try to add that Double? to a String.

    Here's a fixed version:

    extension Double {
        func add(_ value: String) -> Double? {
            guard let numValue = Double(value) else {
                return nil
            }
            return self + numValue
        }
    }