How to Use the Optional Variable in a Ternary Conditional Operator

How do you use the Optional variable in a ternary conditional operator?

You can not assign string value to bool but You can check it str1 is nil or not like this way :

myBool = str1 != nil ? true : false
print(myBool)

It will print false because str1 is empty.

optional argument with ternary operator

If you have the list of arguments, you could make it more concise by using slicing:

args = [x1, x2, x3, x4, x5]
result = f(*args) if five else f(*args[:4])

But it would probably be easier to use a function that accepts an arbitrary number of positional arguments:

def f45(*args):
if len(args) == 5:
# do something
elif len(args) == 4:
# do something else

Swift's Ternary Conditional Operator returning optional from two non-optional values?

@IBOutlets are defined as implicitly unwrapped optionals - that's what the ! stands for at the end of the type. It still is an optional, but you don't have to explicitly unwrap it when used. You could kind of think about this as a promise to the compiler that although this value could be nil at some point, you will use it responsibly and only after it has been set. When inferring the type for deselectThis, the compiler correctly set it Optional<UIButton>, just without the ! (since ! doesn't change the type per-se in this case).

You can either wrap the whole expression in an if let statement or simply provide the explicitly unwrapped typing by doing var deselectThis: UIButton! = ....

Please note that implicitly unwrapped optionals should be used with care and caution. As always - more in the docs.

How to use Java Optional to elegantly replace Ternary operators

To avoid eagerly evaluating else-branches, use orElseGet, which takes an instance of the functional interface Supplier:

return recordA.map(
record -> record.getCreatedAt())
.orElseGet(() -> recordB.get().getCreatedAt());

Initialize boost::optional with ternary operator

The ternary operator requires the left & right to be the same (or convertible) types. none_t and int aren't the same type. You can probably do cond ? boost::optional<int>(5) : boost:none

I don't use boost, so just guessing on syntax based on std::optional, but the following does work:

std::optional<int> opt = cond ? std::optional<int>(5) : std::nullopt;

Why is the let variable = x syntax not working with the ternary operator?

if let is a special Swift form that allows you to rebind an identifier while unwrapping an Optional. A let statement by itself can't rebind an identifier declared in the same scope. Them's the rules.

Furthermore, you cannot use an Optional as if it were a BooleanType, which you're trying to do (since the conditional of ?: has to be a BooleanType).

Also note that print returns () (the empty tuple, also known as the singleton instance of the Void type). So there's no reason to rebind foo to the return value of print.

This works, though it's not good style:

foo != nil ? print("set") : print("nil")

This is good style:

if foo != nil {
print("set")
} else {
print("nil")
}

Or this:

print(foo != nil ? "set" : "nil")

The following is worse in this case, but is a reasonable pattern when you need to transform the wrapped value if set, and provide a default if nil:

print(foo.map { _ in "set" } ?? "nil" )

If you just want to unwrap foo for use later in the function, without increasing the brace nesting level, you can use guard:

guard let foo = foo else {
print("nil")
return // you must return or throw or abort here in a guard statement
}

// Here foo has been rebound and is no longer optional.
print("set to \(foo)")

How to write ternary operator logic for multiple conditions and for optional param?

You could simplify the check to

return !args.drugName || args.drugName.length > 2;
// if empty
// if longer then 2 characters


Related Topics



Leave a reply



Submit