Skip to content

Instantly share code, notes, and snippets.

@sturdysturge
Last active June 9, 2022 22:04
Show Gist options
  • Select an option

  • Save sturdysturge/57299c81278adfe03cbb825107d53310 to your computer and use it in GitHub Desktop.

Select an option

Save sturdysturge/57299c81278adfe03cbb825107d53310 to your computer and use it in GitHub Desktop.
import SwiftUI
protocol MyProtocol {
associatedtype MyAssociatedType: StringProtocol
var myAssociatedType: MyAssociatedType { get }
}
struct MyConformingType: MyProtocol {
var myAssociatedType = "Hello"
}
struct MyOtherConformingType: MyProtocol {
var myAssociatedType = "World"
}
struct MyType {
var anyExample: any MyProtocol = MyConformingType()
var someExample: some MyProtocol = MyConformingType()
}
struct ContentView: View {
@State var myType = MyType()
var body: some View {
VStack {
Text("myType.anyExample: " + String(describing: type(of: myType.anyExample)))
Text("myType.someExample: " + String(describing: type(of: myType.someExample)))
Button("Change") {
myType.anyExample = MyOtherConformingType()
// Will not compile as type is not 'some MyProtocol'
// myType.someExample = MyOtherConformingType()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment