[swift-evolution] [Idea] Set variables to "_" in two-stage init; remove IUO

Jonathan Hull jhull at gbis.com
Thu Jun 16 01:27:47 CDT 2016


I don’t remember a proposal for that, but I would definitely support one.  I use this pattern all the time (usually by initializing to a default value first), and it would be nice to have an explicit/safe way to handle it, (and to avoid waisting cycles creating an object I never use).

Perhaps we should spell it @init or @initHelp:

class MyClass : MySuperClass {

    let x:Int
    let y:String
    let z:Double

    @init func commonSetup() {
        self.y = “My String”
        self.z = 4.2
    }

   init(x: Int) {
        self.x = x
        commonSetup() //No error because commonSetup() sets the value of ‘y’ & ‘z'
        super.init()
   }
}

Basically the @init functions would be inlined into the init.  They would only be callable from inits, and could only be called a single time within each init.

Thanks,
Jon

> I believe there was(was?) already a suggestion to introduce special methods 
> that could be called from initializers. IMO this is a better solution to 
> the problem as you really should not call 'usual' instance method until the 
> instance is fully instantiated(super.init() called in your case):
> 
> class MyClass : MySuperClass {
> 
> 	let x : Int
> 	let y : String  //let!
> 
> 	initfunc calcY(somePatam: Int) -> String {
> 		return ....
> 	}
> 
> 	init(x: Int) {
> 		self.x = x
> 		self.y = assignY(5)
> 		super.init()
> 	}
> }

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160615/6d84b9fe/attachment.html>


More information about the swift-evolution mailing list