Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Optional - Java vs Swift

Java 8: java.util.Optional

private abstract Optional<String> methodThatReturnsOptionalString();

private void useOptionalString() {
	Optional<String> myOptionalString = methodThatReturnsOptionalString();
	if (myOptionalString.isPresent()) {
		String myUnboxedString = myOptionalString.get();
		System.out.format("Optional string had value: %s\n", myUnboxedString);
	} else {
		System.out.println("Optional string was empty");
	}
}

Swift Optional

func methodThatReturnsOptionalString() -> String? {
	return (arc4random() % 2 == 0) ? nil : "Hello world"
}

func useOptionalString() {
	var myOptionalString = methodThatReturnsOptionalString()
	if let myUnboxedString = myOptionalString {
		println("Optional string had value \(myUnboxedString)")
	} else {
		println("Optional string was empty")
	}
}
@knasim
Copy link

knasim commented Feb 28, 2017

did oracle take the concept from swift ?

@muhammadnasr
Copy link

muhammadnasr commented Apr 25, 2019

in Java you must check for null first
if (myOptionalString.isPresent())
should be
if (myOptionalString!= null && myOptionalString.isPresent())

Unfortunately Optional in Java can contains null, so it is does not help much with NullPointerException.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment