You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何避免拼写复杂类型?以Gesture存储属性为例

解决SwiftUI中Gesture作为存储属性的类型问题

你遇到的问题本质是Swift的存在类型(any Gesture)无法直接满足View.gesture(_:)方法对具体Gesture协议类型的要求。以下两种方法可以在保留存储属性的同时,避免手动书写冗长的具体手势类型:

方法一:使用泛型约束

让结构体本身泛型化,编译器会自动推断手势的具体类型,无需手动声明:

struct BorderedRectangle1<G: Gesture>: View {
    let gesture: G

    init(color: Color, border: Bool) {
        self.gesture = TapGesture().modifiers(.option).onEnded {
            // 执行操作
        }.simultaneously(with: TapGesture().modifiers(.command).onEnded {
            // 执行其他操作
        })
    }

    var body: some View {
        Rectangle()
            .gesture(gesture)
    }
}

这种方式保留了手势的原始类型,没有类型擦除的性能开销,适合需要保持类型信息的场景。

方法二:使用类型擦除(AnyGesture)

用AnyGesture包装具体手势,将存储属性的类型声明为AnyGesture(它完全符合Gesture协议):

struct BorderedRectangle1: View {
    let gesture: AnyGesture<Void>

    init(color: Color, border: Bool) {
        let combinedGesture = TapGesture().modifiers(.option).onEnded {
            // 执行操作
        }.simultaneously(with: TapGesture().modifiers(.command).onEnded {
            // 执行其他操作
        })
        self.gesture = AnyGesture(combinedGesture)
    }

    var body: some View {
        Rectangle()
            .gesture(gesture)
    }
}

AnyGesture<Void>中的Void对应TapGesture的Value类型,这种方式不需要结构体泛型化,代码更简洁,适合不需要关注手势具体类型的场景。

内容的提问来源于stack exchange,提问作者g i i k

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 11:42:19