Optional return in C#.Net

Not in the language, no, but you can make your own: public struct Optional<T> { public bool HasValue { get; private set; } private T value; public T Value { get { if (HasValue) return value; else throw new InvalidOperationException(); } } public Optional(T value) { this.value = value; HasValue = true; } public static … Read more

How flatMap API contract transforms Optional input to Non Optional result?

As you’re using the identity transform { $0 }, the compiler will infer that ElementOfResult? (the result of the transform) is equivalent to Element (the argument of the transform). In this case, Element is String?, therefore ElementOfResult? == String?. There’s no need for optional promotion here, so ElementOfResult can be inferred to be String. Therefore … Read more

Get value from one Optional or another

Java 9 and above: firstOptional.or(() -> secondOptional); Java 8 and below If you want to avoid mentioning firstOptional twice, you’d probably have to go with something like firstOptional.map(Optional::of).orElse(secondOptional); or Optional.ofNullable(firstOptional.orElse(secondOptional.orElse(null))); But the most readable variant is probably to simply do Optional<…> opt = firstOptional.isPresent() ? firstOptional : secondOptional.isPresent() ? secondOptional : Optional.empty(); If someone stumbles … Read more

Providing a default value for an Optional in Swift?

Update Apple has now added a coalescing operator: var unwrappedValue = optionalValue ?? defaultValue The ternary operator is your friend in this case var unwrappedValue = optionalValue ? optionalValue! : defaultValue You could also provide your own extension for the Optional enum: extension Optional { func or(defaultValue: T) -> T { switch(self) { case .None: … Read more

What happened to the UIView?() constructor in Swift 3.0?

The following does initialise x to nil, the brackets are entirely superfluous. var x: UIView? return x == nil Will return true Check out the developer docs for more information. https://developer.apple.com/library/content//documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html If you define an optional variable without providing a default value, the variable is automatically set to nil for you: var surveyAnswer: String? // … Read more

unwrapping multiple optionals in if statement

Great news. Unwrapping multiple optionals in a single line is now supported in Swift 1.2 (XCode 6.3 beta, released 2/9/15). No more tuple/switch pattern matching needed. It’s actually very close to your original suggested syntax (thanks for listening, Apple!) if let email = emailField?.text, password = passwordField?.text { } Another nice thing is you can … Read more