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

不使用AnyView扩展View的isHidden方法:返回some View是否可行?

SwiftUI: Using some View instead of AnyView in a custom isHidden modifier

Absolutely, your proposed change is not only feasible but strongly recommended—this is actually a far better approach than sticking with AnyView. Let’s break this down clearly:

Why the some View version works

Swift’s opaque return type (some View) lets you return a concrete View type without exposing its exact details to the caller. In your case, both self.hidden() and self conform to the View protocol, and Swift can automatically infer that they share a compatible underlying type. The compiler has no trouble resolving the return type here, so the code will compile and run flawlessly.

Why this is better than AnyView

  • No unnecessary performance overhead: AnyView forces Swift to erase the concrete type of your view, which adds avoidable performance costs. SwiftUI relies heavily on view type information to optimize rendering, state tracking, and updates—type erasure can break these optimizations, leading to potential unnecessary redraws as your app scales.
  • Cleaner, more idiomatic SwiftUI code: Using some View aligns with SwiftUI’s core design principles, which prioritize preserving type information wherever possible to keep the framework efficient and predictable.

Is it worth worrying about?

Absolutely, this is a worthwhile adjustment. While the performance difference might be negligible in tiny apps, avoiding AnyView becomes more impactful as your app grows in complexity. Plus, the some View version is simply cleaner, more maintainable, and follows best practices for SwiftUI development.

Here’s a side-by-side of your implementations for clarity:

Original implementation (with AnyView):

extension View { 
    func isHidden(_ hidden: Bool) -> AnyView { 
        AnyView(hidden ? self.hidden() : self) 
    } 
}

Improved implementation (with some View):

extension View { 
    func isHidden(_ hidden: Bool) -> some View { 
        return hidden ? self.hidden() : self 
    } 
}

内容的提问来源于stack exchange,提问作者Joseph Beuys' Mum

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 19:32:50