Last active
August 29, 2015 14:25
-
-
Save tjw/6b1056bbadb78b3871bf to your computer and use it in GitHub Desktop.
init-cannot-assign-to-let.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
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.
Oh, and this also works fine:
self.height = { measurement.init(size.height.value) }()
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
Updated so line 17 calls an existing init function; same error though.