Your getData( ) function returns a String value not an optional value. So you should change return type of getData function to optional value type using ? operator
while let always expects an optional value, if your getData function always returns a string value then using while let makes no sense because you are telling the compiler intentionally that getData function will always return a String value and trying to unwrap it, so we shouldn't unwrap a nonoptional value.
Code for error handling ( Written Keeping Swifter in mind )
:
private func nextLine() throws -> String?{
var returnData : String? = ""
if arc4random_uniform(7) != 3 {
returnData = "Genreated Random number other than 3"
}else{
throw NSError(domain: "Generated random number 3", code: 111, userInfo: nil)
}
return returnData
}
do {
while let headerLine = try nextLine() {
//do something with the header
print(headerLine)
}
}catch{
//Handle exception
print(error)
}
nextLine function returns a string telling "Generated Random number other than 3" if generated number is not equal to 3,or else it will throw an exception which can be handled in the catch block.Here I have potentially made nextLine function to return an optional value.If I remove ? from return type of nextLine function. It will give you an error telling "Initializer for conditional value must have optional type not String", it means compiler is trying to unwrap a non optional value which makes no sense.
Consider :
var someIntegerValue = 5
if let x = someIntegerValue
{
// it will give an error
}
Above code will give you an error telling "Intializer for conditional binding must have Optional type,not Int",because even here we are trying to unwrap a non optional value.
If you replace var some = 5 with var some : Int? = 5 it will be all right.
Error/Exception Handling :
you can make use of try keyword before fetching the value which should be inturn written inside do block ,it will either fetch value or it will fire an exception,exception should be handled inside catch block.