0

I have the following issue with using generics in my application. As seen below my GeneralUpdate class enforces a type conformance of T to the ReadingClass, but I cannot assign variable of type Reading in the initializer (marked in the GeneralUpdate class as a comment)

class Reading {
    var readingDate: Date!
    var enteredDate: Date!

    init(readingDate: Date, endDate: Date) {
        self.readingDate = readingDate
        self.enteredDate = endDate
    }
}

class GeneralUpdate<T: Reading> {
    var readingType: ReadingType!
    var dataSource: DataSource!
    var readings: [T]

    init(readingType: ReadingType, dataSource: DataSource, readings: [Reading]) {
        self.readingType = readingType
        self.dataSource = dataSource
        self.readings = readings //produces error "Cannot assign value of type '[Reading]' to type '[_]'"
    }
}

I am not quite sure why this is. I need the reading property to be generic since it can hold different types of readings that are subclassed from the Reading class. I'm new to swift generics and would like some help on how to properly achieve this

2
  • 2
    Unrelated but never ever declare properties as implicit unwrapped optionals which are initialized in an init method with non-optional values. Delete the exclamation marks. No, you won't get a compiler error. Commented Apr 9, 2018 at 12:17
  • thank you. I added that at the beginning at a stage where I wasn't using the init method. I have forgot to update the code Commented Apr 9, 2018 at 12:19

2 Answers 2

3

You need to declare the readings params as [T].

class GeneralUpdate<T: Reading> {
    var readingType: ReadingType
    var dataSource: DataSource
    var readings: [T]

    init(readingType: ReadingType, dataSource: DataSource, readings: [T]) {
        self.readingType = readingType
        self.dataSource = dataSource
        self.readings = readings
    }
}

And please get rid of all that ugly ! Implicitly Unwrapped Optionals.

Sign up to request clarification or add additional context in comments.

Comments

0

Did you try to write something like:

init(readingType: ReadingType, dataSource: DataSource, readings: [T])

Please let me know if this help!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.