这里是获得 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(AColorGradient,等等).

如果我在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中一样)?

谢谢!

推荐答案

它可以用泛型来完成,比如

struct RectangleStyle<S: ShapeStyle> {
    private let style: S

    init(_ style: S) {      // << your init !!
        self.style = style
    }

    func getStyle() -> some ShapeStyle { // << your func !!
        self.style
    }
}

现在是你的测试:

let myStyle = RectangleStyle(LinearGradient(
                    gradient: Gradient(colors: [.red, .blue]),
                    startPoint: .top,
                    endPoint: .bottom
                ))

var body: some View {
    Rectangle()
        .fill(myStyle.getStyle())         // << here !!
        .frame(width: 200, height: 200)
}

使用Xcode 13.4/iOS 15.5进行测试

demo

Test code is here

Swift相关问答推荐

是否有一个Kotlin等价的Swift s @ AddendableReport注释'

Swift C外部实现的Task / Future类类型

与视图交互使工具栏&;标题消失

调度组是否阻止iOS中的主线程?

使用变量(而非固定)的字符串分量进行Swift正则表达式

为什么我的 tableView 没有推送到 tableView 内的 detailViewController?

将弱引用作为类函数引用传递时,弱引用无法按预期工作

从文字创建数组时的 Swift 宏

在 Vapor 4 中使用协议的通用流利查询

数组使用偏移量对自身执行 XOR

符合协议 - 错误?

如何获取 NSRunningApplication 的参数?

swift 如何从 Int 转换?到字符串

无法分配给属性:self 是不可变的,我知道如何修复但需要理解

Swift 覆盖实例变量

Swift 3:小数到 Int

如何停止 NSTimer.scheduledTimerWithTimeInterval

swift - 我可以从我的自定义初始化方法中调用 struct 默认成员初始化吗?

使用 swift IOS 使 UIBarButtonItem 消失

App Tracking Transparency 如何影响显示广告的应用程序? - IDFA iOS14