0

I have an array ZZ of custom object A with property:

String a1

I would like to add the a1 property of all the elements in the array and return an NSNumber value. Since the value a1 is a string, I will also have to cast it into a double on the go too.

I tried to do something on the lines of:

ZZ?.reduce(0, {$0.Int(a1) + $1.Int(a1)})

but getting plenty of errors regarding the syntax.

How can I go about it?

3 Answers 3

1

It should be like this way.

If your string contain Double value:

let result = zz.reduce(0) { $0 + Double($1.a1) ?? 0.0 }

If your string contain Int value:

let result = zz.reduce(0) { $0 + Int($1.a1) ?? 0 }
Sign up to request clarification or add additional context in comments.

Comments

1

As an alternative to using reduce directly on the zz array, you could apply an attempted Double initialization (by the failable init?(_:String) initializer of Double) of the a1 member of each element of zz within a flatMap call on zz, whereafter you apply reduce to sum the elements which were successfully initialized as Double instances.

struct Custom {
  let a1: String
  init(_ a1: String) { self.a1 = a1 }
}

let zz: [Custom] = [Custom("1.4"), Custom("z"), Custom("3.1")]

let sumOfValids = zz.lazy.flatMap{ Double($0.a1) }.reduce(0, +) // 4.5

For the last part (if you really want this)

"I would like to add the a1 property of all the elements in the array and return an NSNumber value".

you can simply make use of the appropriate NSNumber by Double initializer.

Finally, note that none of the above performs attempted casting from String to Double, but attempted initialization of a Double by a String value, making use of the failable by String initializer blueprinted in LosslessStringConvertible, to which Double conforms.

"Since the value a1 is a String, I will also have to cast it into a Double on the go too".

Comments

0

Assuming that a non convertable String to Double means a 0.0 value...

public class Custom
{
    public var theProperty: String

    public init(value: String)
    {
        self.theProperty = value
    }
}

let c1: Custom = Custom(value: "1.1")
let c2: Custom = Custom(value: "a")
let c3: Custom = Custom(value: "3.2")

let array: [Custom] = [ c1, c2, c3 ]

let result: Double = array.map({
    guard let theProperty = Double($0.theProperty) else
    {
        return 0.0
    }

    return theProperty 

})
.reduce(0.0) { $0 + $1 }

print(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.