Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to handle invalid argument in Swift

4 Answers

0 votes
import Foundation

func checkNumber(_ num: Int) {
    guard num >= 0 else {
        print("Error: Negative numbers are not allowed.")
        return
    }
    print("Number: \(num)")
}

checkNumber(56)  // Works fine
checkNumber(-6)  // Prints error message




/*
run:

Number: 56
Error: Negative numbers are not allowed.

*/

 



answered May 21, 2025 by avibootz
0 votes
import Foundation

func validateAge(_ age: Int) {
    precondition(age >= 18, "Age must be 18 or older")
    print("Valid age: \(age)")
}

validateAge(19)  // Works fine
validateAge(14)  // Crashes in debug mode



/*
run:

Precondition failed: Age must be 18 or older: file Main.swift, line 2

*/

 



answered May 21, 2025 by avibootz
0 votes
import Foundation

enum ValidationError: Error {
    case invalidAge
}

func checkAge(_ age: Int) throws {
    if age < 18 {
        throw ValidationError.invalidAge
    }
    print("Valid age: \(age)")
}

do {
    try checkAge(15) // Throws error
} catch {
    print("Error: Invalid age (age < 18)")
}




/*
run:

Error: Invalid age (age < 18)

*/

 



answered May 21, 2025 by avibootz
0 votes
import Foundation

func safeDivide(_ a: Int, _ b: Int) -> Int? {
    guard b != 0 else { return nil }
    return a / b
}

if let result = safeDivide(34, 0) {
    print("Result: \(result)")
} else {
    print("Error: Division by zero.")
}




/*
run:

Error: Division by zero.

*/

 



answered May 21, 2025 by avibootz

Related questions

4 answers 236 views
4 answers 189 views
4 answers 194 views
3 answers 170 views
3 answers 171 views
6 answers 275 views
...