UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Checkpoint 4 - How can I check if number's data type is an Int?

Forums > 100 Days of Swift

Just finished Day 8, Checkpoint 4. Everything is working as expected. However, I created a case where the number passed in is not an integer. I want to make some type of check to throw an error if number is ever anything other than an integer. I know other languages like Python or JavaScript can do this. Is this possible in Swift?

Here is my code:

enum SquareRootError: Error {
  case lessThanOne, greaterThanTenThousand, notAnInt, noRoot
}

func findSquareRoot(_ number: Int) throws -> Int {
  if number < 1 {
    throw SquareRootError.lessThanOne
  }
  if number > 10_000 {
    throw SquareRootError.greaterThanTenThousand
  } 
  for i in 2...100 {
    if i * i == number {
      return i
    }
  }
  throw SquareRootError.noRoot
}

do {
  let result = try findSquareRoot(1231.5)
  print("\(result)")
} catch SquareRootError.lessThanOne, SquareRootError.greaterThanTenThousand {
    print("Out of bounds error.")
} catch SquareRootError.noRoot {
    print("No root error.")
} catch SquareRootError.notAnInt {
    print("Wrong data type.")
} catch {
    print("There was an error.")
}

3      

Swift is a strongly typed language. number will never be anything other than an integer because you declared the parameter to be an Int. If your code tries to pass something in that isn't an Int, the compiler will catch it and you won't even be able to build your project.

Try it. The compiler will flag the line

let result = try findSquareRoot(1231.5)

with an error Cannot convert value of type 'Double' to expected argument type 'Int'

The compiler will make sure that everywhere in your code where you call findSquareRoot you are passing in an Int.

3      

@deebie wants to know if you can determine a variable's type with Swift code:

I want to make some type of check to throw an error if number is ever anything other than an integer.
I know other languages like Python or JavaScript can do this.
Is this possible in Swift?

Playgrounds!

Playgrounds is a great place to slam-jam some code together and test some basic concepts. Let's have a look.

// Paste this code into Playgrounds!

import Foundation

func getMysteryVariable() {
    // What is this going to be? an Int? or a String?
    // It could be either! How can we check?
    let mysteryVariable: Any = Bool.random() ? "deeby" : 42  

    // Try to get the value of mysteryVariable as a string.
    if let itsAString = mysteryVariable as? String {
        // Success! Seems we have a string!
        print("Mystery solved! It's a string: \(itsAString)")
    }

    // Try to get the value of mysteryVariable as an integer.
    if let itsAnInteger = mysteryVariable as? Int {
        // Success! Seems we have an integer!
        print("Mystery solved! It's an integer: \(itsAnInteger)")
    }
}

// In Playgrounds call this function a few times for various results.
getMysteryVariable()  // Run a few times to see
getMysteryVariable()  // results of multiple mystery assignments.
getMysteryVariable()
getMysteryVariable()
getMysteryVariable()

Tip o' the hat to Vincent Pradeilles!
See --> Typcasting Operators

4      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.