Hi..i am trying to create a singleton class .Inside init function/constructor of singleton class some operation is being performed. if any of the operation fails then i have to throw error.
Sample code for the singleton:
//Singleton class
public class Singleton {
// This line is throwing error which is correct because we are not handle error
public static let singleton = Singleton()
//
private init() throws {
//Custom error
throw Custom(code: 19, message: "Message",kind: .customerror)
print("Hello")
}
deinit {
//
print("Deinit")
}
}
Error :
Call can throw, but errors cannot be thrown out of a global variable initializer
Other version :
//Singleton class
public class Singleton {
public static let singleton = {
do {
return try Singleton();
} catch {
print(error)
}
return nil
}()
//
private init() throws {
throw Custom(code: 19, message: "Message",kind: .customerror)
print("Hello")
}
deinit {
//
print("Deinit")
}
}
In above code i am able to catch error inside closure but not able to throw error from closure .
I want to do something like this
//
do {
try Singleton. singleton
} catch {
// Catch error here
print(error)
}
From my current understanding it seem's i cannot catch error .only way i found to check whether there is error or not is to check if value of singleton property is nil or not .
if value of singleton property is nil then there is error .i have to create another property storing error in the Singleton class so the user can check error message .
Question :
Is there any other method available for throwing error from singleton class ?