这里是获得 idea 的playground
import SwiftUI
import PlaygroundSupport
struct RectangleStyle {
public var color: Color? = nil
public var gradient: LinearGradient? = nil
}
struct DemoView: View {
var body: some View {
Rectangle()
.fill(
RectangleStyle(
gradient: LinearGradient(
gradient: Gradient(colors: [.red, .blue]),
startPoint: .top,
endPoint: .bottom
)
).gradient!
)
.frame(width: 200, height: 200)
}
}
PlaygroundPage.current.setLiveView(DemoView())
如你所见,它很难看.我想要的是能够用实现ShapeStyle
的任何对象来构造我的RectangleStyle
(Rectangle
上的fill()
方法所需的协议),并且能够用一个方法检索这个ShapeStyle
(AColor
或Gradient
,等等).
如果我在RectangleStyle
上加上init(style: ShapeStyle)
,我会得到错误Protocol "ShapeStyle" can only be used as a generic constraint because it has Self or associated type requirements
.
如果我试图在我的RectangleStyle
上加func getStyle() -> ShapeStyle
,我也会得到同样的错误.
我如何才能妥善处理这起案件?我们的 idea 是能够用与所需的Rectangle.fill()
类型兼容的任何类型的对象来构造My RectangleStyle
,并具有返回该对象的方法.
是否有可能让Swift知道,如果参数是类型A,那么方法的返回将是相同的类型(就像在TypeScrip中一样)?
谢谢!