if myString then myString else ""
... feels a bit verbose.
Is there a shorter alternative I could use?
myString may be either undefined or a string.
Here's one way:
myString ? ''
And this is what you actually want because it compiles to:
(typeof myString !== "undefined" && myString !== null ? myString : '')
Note that you can use this existence operator for any value, e.g.
myFloat ? 90.8
How about this one:
myString or ""
Use the existential operator:
myString ?= ""
Related
I have a function where string value is defined based on value in dictionary. If value in dictionary is not found, I set it to static string. String is constant (let):
let dict = [ 1: "a",
2: "b" ]
func x() {
let index = someFunctionReturnsInt()
let str = (nil != dict[index]) ? dict[index] : "N/A"
So string cannot possibly be nil. However, when I try to use str, Swift still considers it an optional. For example:
// still inside the same function
os_log("Str is %#", str)
will return a compiler error:
Value of optional type 'String?' must be unwrapped to a value of type 'String'
Thing is, I use this function quite a few times, and adding str ?? "N/A" on every occasion makes no sense. Force-unwrap with str! seems like an overkill: this string is not critical to the app, so I don't think aborting execution if it's missing makes any sense.
So is force-unwrap the only solution, or is there a better way to define a string as non-optional and "never going to be nil"?
The issue is that dict[index] is still returning an optional so str has to be an optional. There are two ways you can fix it
You can use the nil coalescing operator to use dict[index] if its not nil otherwise use "N/A"
let str = dict[index] ?? "N/A"
Another option is to use the dictionary default value subscript
let str = dict[index, default: "N/A"]
You should simply use the nil coalescing operator when defining the str itself. Checking if the value is nil, then still assigning the optional value without unwrapping makes no sense.
let str = dict[index] ?? "N/A"
You should use nil coalescing operator - let str = dict[index] ?? "N/A"
Instead of let str = (nil != dict[index]) ? dict[index] : "N/A"
The reason because str is still optional in your case is because dict[index] is optional even if you are checking it to be no nil. So, swift infers the type of str to be String?
You could also force unwrap because you are already checking it to be no nil like -
let str = (nil != dict[index]) ? dict[index]! : "N/A"
But force unwrapping should be avoided whenever possible
I use Swift 3 and I want to init a String let variable based on a boolean. I know how to do it with a standard if statement with a var variable but not as a one line expression.
With Java i would do:
String str = myBool ? "John" : "Peter";
Is there a equivalent with Swift 3 to not use a var and in a one-line way?
Swift, like Java, supports this ternary operator.
var str = myBool ? "John" : "Peter"
As the title I've just asked, I want to know which case we should use ? = nil
For example :
var text: String? // text will be initialized with nil
var text: String? = nil // text will be assigned to nil
So what is the diffrence between them. When we should use ? = nil
As it says in the Swift Language documentation:
You use optionals in situations where a value may be absent. An optional says: There is a value, and it equals x or there isn’t a value at all
There is no difference between ? and ? = nil. The ? = syntax allows you to assign a default (a word they should perhaps use in the documentation for the sake of clarity) value of your choosing.
So if there is no value at all: ? or, if there is a value, and it equals x, then: ? = <some value>
In javascript to check if a variable was never created, we just do
if (typeof MyVariable !== "undefined"){ ... }
I was wonder how I do that in coffeescript?... I try something like
if (MyVariable?false){ ... }
but this check if MyVariable is a function if so that will call MyVariable(false) if not that will call void(0) or something like that.
Finally I found this easy way to do it:
if (MyVariable?){ ... }
that will generate:
if (typeof MyVariable !== "undefined" && MyVariable !== null){ ... }
UPDATE 04/07/2014
Demo Link
First, to answer your question:
if typeof myVariable isnt 'undefined' then # do stuff
Magrangs' solution will work in most cases, except when you need to distinguish between undefined and false (for example, if myVariable can be true, false or undefined).
And just to point out, you shouldn't be wrapping your conditions in parentheses, and you shouldn't be using curly braces.
The then keyword can be used if everything is on the same line, otherwise use indentation to indicate what code is inside of the condition.
if something
# this is inside the if-statement
# this is back outside of the if-statement
Hope this helps!
This answer is for an older version of coffeescript. See Jaider's answer above if you want a more up to date answer (as of July 2014)
This coffeescript does what you want I think:
if not MyVariable?
MyVariable = "assign a value"
Which produces:
if (!(typeof MyVariable !== "undefined" && MyVariable !== null)) {
MyVariable = "assign a value";
}
N.b. if you make an assignment to MyVariable first, even if you set MyVariable to undefined as in this code, then this compiles to:
if (!(MyVariable != null)) {
MyVariable = "assign a value";
}
I believe this works because the != used by CoffeeScripts Existential Operator (the question mark) coerces undefined to be equal to null.
p.s. Can you actually get if (MyVariable?false){ ... } to work? It doesn't compile for me unless there's a space between the existential operator and false i.e. MyVariable? false which then makes CoffeeScript check it like a function because of the false which it thinks is a parameter for your MyVariable, for example:
if MyVariable? false
alert "Would have attempted to call MyVariable as a function"
else
alert "but didn't call MyVariable as it wasn't a function"
Produces:
if (typeof MyVariable === "function" ? MyVariable(false) : void 0) {
alert("Would have attempted to call MyVariable as a function");
} else {
alert("but didn't call MyVariable as it wasn't a function");
}
typeof MyVariable isnt "undefined"
from js2coffee
In addition to Jaider's answer above (I couldn't comment due to insufficient reputation), be careful that it's a different case if it's something inside an object/array:
someArray['key']?
will be converted to:
someArray['key'] != null
Screenshot from js2coffee.org:
I just use:
if (myVariable)
//do stuff
As undefined is falsy it will only do stuff if myVariable is not undefined.
You just have to be aware that it will 'do stuff' for values that are 0, "" and null
The cleanest way I've found to assign a variable to an undefined and not-null variable is using unless:
unless ( myVar? )
myVar = 'val'
Why not just use the OR idiom?
myVar or 'val'
So, the result will equal myVar, unless it is undefined in which case it will equal 'val'.
I have used the below function
while(labelZ.text!=0)
but I'm getting a typecast error.
To check if a string is not set, use:
labelZ.text == nil
To check if a string is an empty string, use:
[labelZ.text isEqualToString:#""]
To check if a string equals "0", use:
[labelZ.text isEqualToString:#"0"]
Use nil instead of 0.
Try this
while((int)labelZ.text!=0)