[swift-users] initializer with alternative

J.E. Schotsman jeschot at xs4all.nl
Mon Jul 25 12:46:46 CDT 2016


Hello,

I have a class that can be initialized from a file.
I would like to add a convenience init that uses a backup file if necessary.
Writing a function for this is easy, but I can’t manage to turn this into an init function.

import Foundation

class TestClass
	{
	init( fromFile file:NSURL ) throws
		{
		
		}
	
	convenience init( fromFile file:NSURL, fromBackupFile backupFile:NSURL ) throws
		{
		do { try self.init( fromFile:file ) }
		catch {
			do { try self.init( fromFile:backupFile ) } // error: 'self' used inside 'catch' block reachable from self.init call
			}
		}
	}

func MakeTestClass( fromFile file:NSURL, fromBackupFile backupFile:NSURL ) throws -> TestClass
	{
	do { return try TestClass( fromFile:file ) } 
	catch { do { return try TestClass( fromFile:backupFile ) } } 
	}

Any suggestions?


More information about the swift-users mailing list