Binary operator '-' cannot be applied to two (NSDate?) operators - sum

Trying to get a total amount of time from a start time and end time.
I have the DateFormatter correct as in Extension.swift below but I am getting confused on the way to calculate bottomtime - starttime.
Any help is appreciated. Thanks
Extension.swift
extension NSDate{
var bottomtimestringValue: String{
return self.toString()
}
func tobottomtimeString() -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MMM-dd"
let str = formatter.stringFromDate(self)
return str
}
}
extension String{
var bottomtimedateValue: NSDate?{
return self.toDate()
}
func tobottomtimeDate() -> NSDate? {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MMM-dd"
if let date = formatter.dateFromString(self) {
return date
}else{
// if format failed, Put some code here
return nil // an example
}
}
}
Adddivelogviewcontroller.swift
var a = (textFieldStartTime.text.starttimedateValue)
var b = (textFieldEndTime.text.endtimedateValue)
var sum = b - a
textFieldBottomTime.text = "\(sum)"

That's correct-- the - operator is not defined for NSDate?, so you can't find the difference that way. Since a and b are both NSDate?, you could find the difference like this:
if let dateA = a, dateB = b {
let difference = dateA.timeIntervalSinceReferenceDate - dateB.timeIntervalSinceReferenceDate
}
Here, difference's type will be NSTimeInterval?.
Or if you prefer, you could add a definition of - for NSDate?, which might look like this:
func -(lhs:NSDate?, rhs:NSDate?) -> NSTimeInterval? {
if let left=lhs, right=rhs {
return left.timeIntervalSinceReferenceDate - right.timeIntervalSinceReferenceDate
} else {
return nil
}
}
Add that and you can use - above.

OK, not really sure if thats working or not but i get no errors. What I need this to do calculate after the end time picker OK botton is pressed
func OK3ButtonTapped(sender: UIBarButtonItem) {
self.textFieldEndTime.endEditing(true)
self.textFieldEndTime.text = endtimePickerView.date.endtimestringValue
var a = (textFieldStartTime.text.starttimedateValue)
var b = (textFieldEndTime.text.endtimedateValue)
var difference: String = ""
if let dateA = a, dateB = b {
let difference = dateA.timeIntervalSinceReferenceDate - dateB.timeIntervalSinceReferenceDate
}
textFieldBottomTime.text = "\(difference)"
}

Related

How to fold results from a few async calls

I want to get the results of my asynchronous function and use them in the fold function. Here's my function that didn't work:
private fun sendOrderStatus(list: List<OrderStatusEntity>) : Single<Boolean> {
return Single.just(
list.fold(true) { initial, item ->
if (!item.isTerminal()) {
val info = OrderStateParameters(
lon = item.orderStatusLon!!,
lat = item.orderStatusLat!!,
datetime = item.orderStatusDate!!
)
val state = OrderState(item.orderId, item.toSend(), info)
return tasksUseCase.sendOrderStatusForWorker(state)
.doOnSuccess { markSent(item) } // side calling
.flatMap {
return#flatMap initial && it.isSuccess // that result should be used in *fold*-function
}
} else // stub result
true
}
)
}
So, I intend to return a Single that will contain the aggregated result of all tasksUseCase.sendOrderStatusForWorker(state) calls.
Thank for any helps!

Trouble converting NSData Objective-C code to Swift

I've been having issues converting an Objective-C snippet to Swift that uses NSData and CoreBluetooth. I have looked at this question and a couple others dealing with NSData in Swift but haven't had any success.
Objective-C Snippet:
- (CGFloat) minTemperature
{
CGFloat result = NAN;
int16_t value = 0;
// characteristic is a CBCharacteristic
if (characteristic) {
[[characteristic value] getBytes:&value length:sizeof (value)];
result = (CGFloat)value / 10.0f;
}
return result;
}
What I have so far in Swift (not working):
func minTemperature() -> CGFloat {
let bytes = [UInt8](characteristic?.value)
let pointer = UnsafePointer<UInt8>(bytes)
let fPointer = pointer.withMemoryRebound(to: Int16.self, capacity: 2) { return $0 }
value = Int16(fPointer.pointee)
result = CGFloat(value / 10) // not correct value
return result
}
Does the logic look wrong here? Thanks!
One error is in
let fPointer = pointer.withMemoryRebound(to: Int16.self, capacity: 2) { return $0 }
because the rebound pointer $0 is only valid inside the closure and must
not be passed to the outside. Also the capacity should be 1 for a
single Int16 value. Another problem is the integer division in
result = CGFloat(value / 10)
which truncates the result (as already observed by the4kman).
Creating an [UInt8] array from the data is not necessary, the
withUnsafeBytes() method of Data can be used instead.
Finally you could return nil (instead of "not a number") if no
characteristic value is given:
func minTemperature() -> CGFloat? {
guard let value = characteristic?.value else {
return nil
}
let i16val = value.withUnsafeBytes { (ptr: UnsafePointer<Int16>) in
ptr.pointee
}
return CGFloat(i16val) / 10.0
}
You should make the return value optional and check if characteristic is nil in the beginning with a guard. You should also explicitly convert the value to CGFloat, then divide it by 10.
func minTemperature() -> CGFloat? {
guard characteristic != nil else {
return nil
  }
let bytes = [UInt8](characteristic!.value)
let pointer = UnsafePointer<UInt8>(bytes)
let fPointer = pointer.withMemoryRebound(to: Int16.self, capacity: 2) { return $0 }
let value = Int16(fPointer.pointee)
result = CGFloat(value) / 10
return result
}

iOS - Realm Query is not working properly

I am using Swift(2.2) Realm Framework as doing with document. Here is my codes.
class SwipedAsset: Object{
dynamic var identifier = ""
dynamic var createdAt = ""
}
// save data
let realm = try! Realm()
let fileName = asset.originalFilename
if fileName != nil {
let swipedAssets = realm.objects(SwipedAsset.self).filter("identifier == '\(fileName!)'")
let assetCount = swipedAssets.count
if assetCount == 0 {
let swipedAsset = SwipedAsset()
if asset.originalFilename != nil {
swipedAsset.identifier = asset.originalFilename!
}
if asset.creationDate != nil {
let year = String(asset.creationDate!.year)[2...3]
let key = "\(asset.creationDate!.monthName) \(year)"
swipedAsset.createdAt = key
}
let realm = try! Realm()
try! realm.write{
realm.add(swipedAsset)
}
}
}
// load data
let realm = try! Realm()
let swipedAssets = realm.objects(SwipedAsset.self).filter("createdAt == '\(key)'")
let lastObject = swipedAssets.last
print(lastObject.identifier)
print(lastObject.createdAt)
Here, values are all "", "" Nothing, But swipedAssets.count = 3 I thought it means realm's query is working properly.
What's wrong with me ? Thanks for any help.
Please do not try to debug with breakpoint.

ActionScript 2.0 Random Boolean Function not working

I have the below code which show be randomly true and randomly false. But in my case its always being false. Any help is appreciated. Thanks.
In the below code tail and heads are the tow buttons.
on(release)
{
var guess:Boolean = Boolean(Math.round(Math.random()));
var input:Boolean;
if (event.target.name == "tail"){
input = true;
}
else if (event.target.name == "heads"){
input = false;
}
if (guess == input){
var newresult = Number(income.text) + Number(amount.text);
income.text = Number(newresult);
}
else{
var newresult = Number(income.text) - Number(amount.text);
income.text = Number(newresult);
}
}
This will also work:
on(release)
{
var guess:Boolean = Boolean(Math.floor(Math.random()*2));
if (guess){
result.text = "Your Guess is corrent";
var newresult = Number(income.text) + Number(amount.text);
income.text = Number(newresult);
}
else{
result.text = "Your Guess is wrong";
var newresult = Number(income.text) - Number(amount.text);
income.text = Number(newresult);
}
}
You dont need the event.target.name because the function is within the event handler of each button. So you can just use a random boolean. Event.target.name also doesnt work in AS2.0

convert date from json format to other formats in sencha

Can anyone tell me how to convert date from Json data to normal date format in sencha.
var df = this.dateFormat;
if (!v) {
return v;
}
if (Ext.isDate(v)) {
return v;
}
if (df) {
if (df == 'timestamp') {
return new Date(v * 1000);
}
if (df == 'time') {
return new Date(parseInt(v, 10));
}
return Date.parseDate(v, df);
}
var parsed = Date.parse(v);
return parsed ? new Date(parsed) : null;
Thanks in advance
The Ext.Date class is what you're looking for. Try something like:
var parsed = Ext.Date.parse(valueFromJSON, "Y-m-d g:i:s A");
The Ext.Date.parse method returns a Date.