Skip to content

Instantly share code, notes, and snippets.

@tjw
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjw/6b1056bbadb78b3871bf to your computer and use it in GitHub Desktop.
Save tjw/6b1056bbadb78b3871bf to your computer and use it in GitHub Desktop.
init-cannot-assign-to-let.swift
public class Measurement {
public let value: Double
public required init(_ value:Double) {
self.value = value
}
}
public struct Size {
public let width:Measurement
public let height:Measurement
public init(measurement:Measurement.Type, size:Size) {
self.width = Measurement(0.0)
// with this line, both self.width and self.height assignments generate "cannot assign to property".
self.height = measurement.init(size.height.value)
// commenting out the above line and using this one instead, there is no complaint about assigning to the "let" property in init()
//self.height = Measurement(0.0)
}
}
@dwineman
Copy link

Weirdly, if you move the troublesome code outside the body of Size.init()...

// insert at top level:
func makeMeasurement(m: Measurement.Type, size: Size) -> Measurement {
  return m.init(size.height.value)
}
// and replace line 17 with:
self.height = makeMeasurement(measurement, size: size)

...then it compiles just fine. But if you then move makeMeasurement() to be a local function inside Size.init(), it breaks again! So bizarre.

@dwineman
Copy link

Oh, and this also works fine:

self.height = { measurement.init(size.height.value) }()

@tylerarnold
Copy link

you are passing struct Size inside of Size's init : init(measurement:Measurement.Type, size:Size)
this seems like it would cause the compiler to think there is a circularity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment