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 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.
765 M2 Mac fails to install rbenv install 3.1.3 due to errors
1225 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
751 Error in x, y, and format string must not be None
633 PHP ssh2_scp_send fails to send files as intended
768 GDB gets version error when attempting to debug with the Presense SDK (IDE)
© 2025 OneMinuteCode. All rights reserved.