Working With Files
Lesson 1 of 48 in Coddy's Swift for Ruby Developers course.
Bring Ruby experience with objects, blocks and dynamic method calls into Swift console programs. Ruby executes source through its runtime; these Swift files compile together as one module. You do not require sibling Swift files. Put import Foundation in each file that needs those APIs, and reserve top-level statements for main.swift with helper functions and types in separate files.
Run the complete first task and inspect Functions.swift. Later exercises ask you to implement required APIs and return text from solve, while the locked driver handles input, checks and printing. The comparisons use Ruby 3.3 and Swift standard-library console programs, with explicit attention to value copying, optional absence, protocol contracts and object lifetime.
Challenge
EasyRun the supplied program. Input is one ASCII name of 1 to 20 letters. welcome(_:) returns Hello, followed by that name. The driver prints it. All Swift files compile together; top-level statements belong only in main.swift. In this multi-file Swift executable, main.swift is the entry file; Ruby does not require that filename. Free functions live in Functions.swift; later named types each have their own file.
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 welcome("Ada") == "Hello, Ada"
}
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") }
All lessons in Swift for Ruby Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry RulesPractice on your own: Swift playground