Menu
CoddyTech

Optionals and Binding

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

A Kotlin nullable type and a Swift Optional both represent a value that may be absent. Swift writes Int? and uses nil, where Kotlin uses null. Optional binding with if let unwraps a present value into a new nonoptional binding. The nil-coalescing operator ?? supplies a fallback, corresponding to Kotlin Elvis ?: for this common case. Optional chaining in Swift also produces an optional result. Do not translate Kotlin force-unwrapping into Swift force-unwrapping without checking the input contract; an absent value causes a runtime trap. Keep absence visible until you have chosen the appropriate fallback or control-flow branch.

Kotlin

fun main() {
    val label: String? = null
    println(label?.length ?: 4)
    val present: String? = "cat"
    println(present?.length ?: 4)
}

Swift

let label: String? = nil
print(label?.count ?? 4)
let present: String? = "cat"
if let text = present { print(text.count) }
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 Kotlin Developers

Practice on your own: Swift playground