Menu
CoddyTech

Optionals and Binding

Lesson 7 of 48 in Coddy's Swift for Java Developers course.

A Java reference may be null unless a separate convention or tool forbids it. Swift encodes absence in the type: String? is an optional string, while String requires a value. An optional is a value with either no wrapped value or one wrapped value.

The examples handle a missing room nickname. Java checks the reference against null. Swift if let unwraps an optional into a nonoptional local binding within the success branch. ?? supplies a fallback when an optional is nil. Neither technique needs a forced unwrap.

Java: complete program

Main.java

import java.util.*;
import java.util.function.*;
public class Main {

  public static void main(String[] args) throws Exception {
    String nickname = null;
    System.out.println(nickname == null ? "Unnamed" : nickname);
  }
}

Swift: complete program

main.swift

import Foundation
let nickname: String? = nil
if let name = nickname {
    print(name)
} else {
    print("Unnamed")
}

Java Optional is a library container, not the default type of every nullable reference. Swift Optional is integrated with the type system; assigning nil to a plain String is a type error.

challenge icon

Challenge

Easy

Implement port(_:) -> Int?: return a parsed integer only in 1 through 65535, otherwise nil. Input is one nonempty ASCII token of at most 10 characters, either decimal digits, an optional leading minus, or letters. Output the value or invalid.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
return port("443") == 443 && port("0") == nil && port("oops") == nil && port("65536") == nil
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for Java Developers

Practice on your own: Swift playground