I want to calculate the sum in the array.

Asked 2 years ago, Updated 2 years ago, 73 views

import UIKit
import CoreMotion

classViewController:UIViewController {

@IBOutlet weak var Myaccelx: UILabel!
@IBOutlet weak var accelxaddition: UILabel!


let motionManager: CMMotionManager= CMMotionManager()
vartimer —NSTimer=NSTimer()
var countArray=[String]( ) // Array
var bele = 20
varkazu = 0
varj = 0
var num = 0


override func viewDidLoad(){
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from anib.

    // Initialize MotionManager
    motionManager.deviceMotionUpdateInterval=0.05//20Hz

    // Start motion data acquisition
    motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler: {
        deviceManager, error in
        varaccel:CMACceleration=deviceManager.userAcceleration

        self.countArray.append("\(accel.x)")

        if self.countArray.count>=self.bele{
            self.countArray.removeAtIndex(0)
        }

        self.Myaccelx.text=("\(self.countArray)")

        self.timer = NSTimer.scheduledTimerWithTimeInterval (1, target:self, selector: "Count", userInfo:nil, repeat:true)
    })
}


func Count() {



}

override funcdidReceiveMemoryWarning(){
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
 }


}

Regarding the above program, I would like to calculate the total in the array when I process the count.
I can calculate acceleration 20 times per second (0.05 Hz), so I would like to calculate the total value every second.
How can I call you?

swift xcode

2022-09-30 20:57

1 Answers

Swift provides functions called map and reduce for arrays (Array.
(There is also a function called filter, but it is omitted here.)

let floatArray: Double = [1.0, 1.1, 1.2, 1.3, 1.4, 1.5]

let mapResult: Double = floatArray.map({(a:Double)->Double in
    a* 2.0
})

// output: [2, 2.2, 2.4, 2.6, 2.8, 3]

letreduceResult: Double=floatArray.reduce(0.0,combin:{
    (a: Double, b: Double) - > Double in
    a+b
})

// output —7.5

For the sample code above, the map function multiplies all elements of the array by 2.0.
The reduce function adds the value of the elements to the previous results, and adds all the elements as a whole.
You can find a lot of Japanese information about both functions online, so please study them.

The reduce function will help you with your questions.Therefore, I think it is useless to convert real numbers (double, float, etc.) into strings when you have the purpose of calculating.


2022-09-30 20:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.