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")
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment