Hi Team!
I hope you are doing well.
I'm sorry for such a minor ideas but for my project they will make code more compact.
Assigning optional only if it has a value. E.g.: var a: Int? var b = 0
instead of: if (a != nil ) { b = a }
use short:
b =? a
I can do it by implementing a custom operator but I think it's good to have it in the standard library: infixoperator =? : AssignmentPrecedence extension Int { staticfunc =?(left: inout Int, right: Int?) { if right != nil { left = right! }}
}
The second idea for the conditional assignment I don't know how to implement by myself. E.g. let c = 0 var d = 0
we have a ternary operator for the case when we want to assign an alternative value in case some condition is false:
d = c > 0 ? c : 1
but if we don't want to use any alternative then we need to write code like this:
if (c > 0) { d = c }
My suggestion is to simplify the syntax somehow. E.g.:
d = c > 0 ? c or d = c > 0 ? c : _
I understand that the proposals are looking as they're out of thin air, but when you are reading dozens of parameters from the external source it's good to make it as short as possible.
Similarly, you can write this as d = max(c, d), although I prefer the original.
Do you have any other examples where the syntactic sugar for ternary operations might offer an improvement? Syntactic sugar additions have a very high bar for entry into the language.
I do the same in my code for both proposals - if condition is false then I assign the variable itself.
But I think it looks not quite elegant:
b = a ?? b
d = c > 0 ? c : d
Both proposals are not just for Int. It can be applied to String as well or any other types:
if (str != "") { str = "some string")
The idea is that if the condition is false then no assignment should be done.
The same as in the 1st proposal - if the value is nil then don't do the assignment at all.
I've found both solutions for myself but I still think it's good to have it in the standard library: infixoperator ?= : AssignmentPrecedence func ?=< T >(lhs: inout T, rhs: T?) { if rhs != nil { lhs = rhs! } } func ?=< T >(lhs: inout T, rhs: (Bool, T)) { if rhs.0 { lhs = rhs.1 } }