Making Applications with Swift
Building Applications with Swift
Section titled “Building Applications with Swift”In this chapter, we will create two simple applications using Swift and UIKit to understand basic iOS development concepts.
First Application – “Guess the Number”
Section titled “First Application – “Guess the Number””We’ll build an application called “Guess the Number”. This app will generate a random number, and the user will try to guess it.
Project Setup: Create a new iOS project in Xcode using the “App” template, select “Storyboard” for the Interface, and “Swift” for the language. Name it “GuessTheNumber” or similar.
Interface Setup (Main.storyboard):
- Drag a
UILabelonto the main view. Change its text to “Guess the Number (0-9)”. Adjust its font, color, and alignment as desired. - Drag a
UITextFieldbelow the label. Set its placeholder text to “Enter your guess”. Set its keyboard type to “Number Pad” for easier numeric input. - Drag a
UIButtonbelow the text field. Change its title to “Guess”. - Drag another
UILabelbelow the button. This will display the result (e.g., “You’re right!” or “Wrong!”). Clear its initial text and ensure it has enough lines to display messages (set Lines to 0 for dynamic height or 2 for fixed height).
Your view layout should now have a title label, an input text field, a guess button, and a result label, arranged vertically.
Connecting UI to Code (ViewController.swift):
Open Main.storyboard and ViewController.swift side-by-side using the Assistant editor.
- Control-drag from the
UITextFieldto yourViewController.swiftfile to create an@IBOutlet. Name itguessTextField. - Control-drag from the result
UILabelto create an@IBOutlet. Name itresultLabel. - Control-drag from the
UIButtonto create an@IBActionfor the ‘Touch Up Inside’ event. Name the methodguessButtonTapped.
Application Logic
Section titled “Application Logic”The logic is straightforward: The app will generate a random integer between 0 and 9 (inclusive). When the user enters a number and taps the “Guess” button, the app will compare the user’s input with the randomly generated number and display an appropriate message in the resultLabel.
Implementing the Logic
Section titled “Implementing the Logic”To generate a random number between 0 and 9, we’ll use Swift’s Int.random(in:) method.
// Inside your ViewController class, you might want to generate the number// when the view loads or each time the button is pressed.// For this example, let's generate it inside the button action for simplicity,// meaning a new number is generated for each guess.
// Or, for a persistent number until guessed or reset:// var targetNumber: Int = 0// override func viewDidLoad() {// super.viewDidLoad()// generateNewTargetNumber()// }// func generateNewTargetNumber() {// targetNumber = Int.random(in: 0...9)// }The core logic will be inside the guessButtonTapped action method.
@IBAction func guessButtonTapped(_ sender: UIButton) { let randomNumber = Int.random(in: 0...9) // Generates a new random number each time
guard let userInputText = guessTextField.text, !userInputText.isEmpty else { resultLabel.text = "Please enter a number." return }
guard let userGuess = Int(userInputText) else { resultLabel.text = "Invalid input. Please enter a whole number." return }
if userGuess == randomNumber { resultLabel.text = "You're right! The number was \(randomNumber)." resultLabel.textColor = .systemGreen } else { resultLabel.text = "Wrong! It was \(randomNumber). Try again!" resultLabel.textColor = .systemRed }
// Optional: Clear the text field after a guess // guessTextField.text = ""}Your guessButtonTapped function should now contain this logic. This setup demonstrates basic UI interaction, input handling, and conditional logic.
Running the Application: Build and run your application on a simulator or device. You should see the UI you designed. Enter a number in the text field and tap “Guess”. The result label will update accordingly.
For example, if you enter “5” and the random number was 7, the label might say “Wrong! It was 7. Try again!”. If you enter “3” and the random number was 3, it would say “You’re right! The number was 3.”
This completes the “Guess the Number” application. Experiment by modifying it, perhaps by giving a limited number of tries or hints.
Second Application – “Is It Prime?”
Section titled “Second Application – “Is It Prime?””In this application, the user will enter a number, and the app will determine if it’s a prime number.
- Project Setup: Create a new iOS project similar to the first one, naming it “IsItPrime”.
- Interface Layout: The UI will be similar to the “Guess the Number” app: a
UILabelfor instructions (e.g., “Enter a number to check if it’s prime”), aUITextFieldfor number input (set keyboard to Number Pad), aUIButton(e.g., “Check Prime”), and anotherUILabelfor the result. - Connect UI to Code: Create
@IBOutlets for the text field (numberTextField) and the result label (primeResultLabel), and an@IBActionfor the button (checkPrimeButtonTapped).
The visual layout will consist of a title, an input field for the number, a button to trigger the check, and a label to display whether the entered number is prime or not.
What is the Logic for Primality Test?
Section titled “What is the Logic for Primality Test?”A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples: 2, 3, 5, 7, 11 are prime. 4 (2x2), 6 (2x3), 1 (by definition) are not prime.
Algorithm:
- Handle edge cases: Numbers less than 2 are not prime.
- The number 2 is the smallest prime number.
- For numbers greater than 2, check for divisibility from 2 up to the square root of the number. If it’s divisible by any number in this range, it’s not prime. If no divisors are found, it’s prime.
Implementing the Primality Test
Section titled “Implementing the Primality Test”The core logic will be in the checkPrimeButtonTapped action and a helper function.
// Helper function to check for primalityfunc isPrime(_ number: Int) -> Bool { if number <= 1 { return false } // Numbers 1 or less are not prime if number <= 3 { return true } // 2 and 3 are prime if number % 2 == 0 || number % 3 == 0 { return false } // Eliminate multiples of 2 and 3
var i = 5 while i * i <= number { if number % i == 0 || number % (i + 2) == 0 { return false } i += 6 } return true}
@IBAction func checkPrimeButtonTapped(_ sender: UIButton) { guard let inputText = numberTextField.text, !inputText.isEmpty else { primeResultLabel.text = "Please enter a number." return }
guard let number = Int(inputText) else { primeResultLabel.text = "Invalid input. Please enter a whole number." return }
if isPrime(number) { primeResultLabel.text = "\(number) is a prime number!" primeResultLabel.textColor = .systemGreen } else { primeResultLabel.text = "\(number) is not a prime number." primeResultLabel.textColor = .systemRed }}The checkPrimeButtonTapped function will parse the input, call the isPrime helper function, and update primeResultLabel with the outcome. The isPrime function contains the optimized logic for determining primality.
Running the Application: Build and run the “IsItPrime” app. Enter various numbers (e.g., 1, 2, 7, 10, 29, 99) to test its functionality. The result label should update correctly based on whether the number is prime or not.
For instance, entering “29” should result in “29 is a prime number!”, while entering “10” should result in “10 is not a prime number.”