/* The challenge is this: write a function that accepts an integer from 1 through 10,000, and returns the integer square root of that number. That sounds easy, but there are some catches: You can’t use Swift’s built-in sqrt() function or similar – you need to find the square root yourself. If the number is less than 1 or greater than 10,000 you should throw an “out of bounds” error. You should only consider integer square roots – don’t worry about the square root of 3 being 1.732, for example. If you can’t find the square root, throw a “no root” error. */ enum rootError: Error{ case lessThan1, moreThan10_000, noRoot } func squareRootFinder (input: Int) throws -> Int { if input < 1 { throw rootError.lessThan1 } if input > 10_000 { throw rootError.moreThan10_000 } for i in 1...100 { let calculation:Double = Double(input) / Double(i) print("\(input) / \(i) = \(calculation)") if calculation == Double(i) { print("Root found as \(i)!") return i } } throw rootError.noRoot } let number = 36 do { try squareRootFinder(input: number) } catch rootError.lessThan1 { print("Your number is less than 1") } catch rootError.moreThan10_000 { print("Your number is more than 10,000") } catch rootError.noRoot { print("Your number has no root") } catch { print("You have an error") }
Write, Run & Share Swift code online using OneCompiler’s Swift online compiler for free. It’s a fast and user-friendly platform to explore Swift programming right from your browser. Ideal for students, beginners, and professionals looking to prototype or test Swift code.
Swift is a powerful and intuitive programming language developed by Apple for iOS, macOS, watchOS, and tvOS app development. It's designed to be safe, fast, and expressive, with modern features like optionals, closures, and type inference.
The following is a simple Swift program that prints a greeting:
import Foundation
print("Hello, OneCompiler!")
OneCompiler’s Swift editor supports standard input via the I/O tab. Here’s a sample Swift program that takes a user’s name and prints a greeting:
import Foundation
if let name = readLine() {
print("Hello, \(name)!")
}
var age = 25 // Mutable variable
let name = "Swift" // Constant
Type | Description |
---|---|
Int | Whole numbers |
Double | Decimal numbers |
String | Sequence of characters |
Bool | true or false |
Array | Ordered collection |
Dictionary | Key-value pairs |
let score = 75
if score >= 50 {
print("Pass")
} else {
print("Fail")
}
for i in 1...5 {
print(i)
}
var i = 1
while i <= 5 {
print(i)
i += 1
}
var j = 1
repeat {
print(j)
j += 1
} while j <= 5
func greet(name: String) {
print("Hello, \(name)!")
}
greet(name: "OneCompiler")
func add(a: Int, b: Int) -> Int {
return a + b
}
This guide provides a quick reference to Swift programming syntax and features. Start writing Swift code using OneCompiler’s Swift online compiler today!