Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
William Forbes
21,469 PointsReadLine()
Hello, Does anyone have a familiarity with using the readLine() function command that would be able to provide some resources on how to properly use it? It appears to return an optional but I am having issues unwrapping it. Can it parse information passed to and find an int/double or will it always be a string? EDIT: Also I mean specifically in Swift 2.0 as opposed to Obj-C
1 Answer
jcorum
71,830 PointsHere's an example from the net:
In order to catch errors that are thrown, we use the do-catch construct.
Let’s demonstrate this by writing a function which will read in user input
from the command line (using Swift 2.0’s nifty new readLine function),
and try to parse it as an IP address:
func tryNumericisingIP() {
// Get the value from the user
print("Enter four-part IP here: > ", terminator: "")
let maybeInput = readLine(stripNewline: true)
// Only continue if we actually received a value
guard let input = maybeInput else {
return
}
// Try numericising the user-provided IP. Handle any errors.
do {
let numericValue = try numericiseIPAddress(input)
print("Your IP address, \(input) is equal to \(numericValue)")
} catch IPError.TooFewComponents {
print("IP address had fewer than 4 components")
} catch IPError.TooManyComponents {
print("IP address had more than 4 components")
} catch let IPError.OctetWasBad(octet) {
print("Octet number \(octet) was invalid - either non-numeric or out of bounds")
} catch {
// This shouldn't be necessary, but the compiler complains about
// exhaustiveness. Maybe an early beta seed bug.
print("Encountered an unknown error \(error)")
}
}
Source: http://austinzheng.com/2015/06/08/swift-2-control-flow/