0

Here's my struct that contains a generic:

struct SupportOptions<S> where S: ListStyle {
    var text: String = ""
    var listStyle: S
}

/**
 Allow initializing without a `listStyle` https://stackoverflow.com/a/64530006/14351818
 */
extension SupportOptions where S == InsetGroupedListStyle {
    init(text: String = "") {
        self.text = text
        self.listStyle = InsetGroupedListStyle()
    }
}

I then create an instance of it like this:

class ViewController: UIViewController {
    var options = SupportOptions()
}

But, when I try changing options.listStyle, it doesn't work.

options.listStyle = InsetListStyle()

Cannot assign value of type 'InsetListStyle' to type 'InsetGroupedListStyle'

aheze
  • 24,434
  • 8
  • 68
  • 125
  • 2
    Not my downvote but thats not how generic works. Once you initialize the property you define its type. IMO There is no way to change it later. You need to create a new SupportOptions object. – Leo Dabus Nov 01 '20 at 02:04
  • 1
    I didn't downvote, but you are doing something very wrong. You are mixing SwiftUI and UIKit in a very weird way/using SwiftUI incorrectly... SwiftUI types don't like to be assigned like that. You probably need to make your own enum wrapper for `ListStyle` and use that instead, then write a extension method on `List` that takes your wrapper enum and sets the list style. – Sweeper Nov 01 '20 at 02:04
  • @LeoDabus got it. – aheze Nov 01 '20 at 02:28
  • @Sweeper enum sounds good. – aheze Nov 01 '20 at 02:29
  • 2
    Downvoted for not showing a use case, which will lead you to keep asking questions that won't be helpful to other people, and also, for naming it `S` instead of `ListStyle. A question that can't help other people should be paid to a consultant to be answered, instead. –  Nov 01 '20 at 03:26
  • @Jessy fair, will keep in mind next time. The `S` was from a previous answer though... – aheze Nov 01 '20 at 03:27
  • @Sweeper I ran into [more errors](https://stackoverflow.com/q/64634800/14351818) unfortunately... – aheze Nov 01 '20 at 17:31

1 Answers1

3

When you call SupportOptions() with no arguments it's actually calling init(text:) with an empty string for the optional text argument. Your init(text:) method defines the generic constraint S to be of type InsetGroupedListStyle. Once your generic constraint is defined you can't assign anything other than an InsetGroupedListStyle instance to listStyle. That is why your InsetListStyle assignment is failing.

If you want listStyle to be of type InsetListStyle you need to specify that at the time of instantiation:

class ViewController: UIViewController {
    var options = SupportOptions(text: "", listStyle: InsetListStyle())
}
Rob C
  • 4,877
  • 1
  • 11
  • 24