今日已更新 232 条资讯 | 累计 29374 条内容
关于我们

Swift Protocols — Opaque Return Types and the Mystery of `some` 🔮

Gamya 2026年08月08日 14:35 0 次阅读 来源:Dev.to

You've seen some View in every SwiftUI file you've ever opened. Now let's find out what it actually means, why it exists, and why returning a plain protocol doesn't work the same way. Fair warning: this topic is genuinely one of the more brain-bendy things in Swift. I'm going to tell you upfront that you don't need to fully understand the internals to keep going — but you do need to know it exists and roughly what it's doing, because you've already been using it every single time you've written a SwiftUI view. That some View in every SwiftUI file? That's an opaque return type. And now we're going to actually understand what that means. 🍥 Let's Start With Something That Works Two simple functions: func getRandomJutsu () -> Int { Int . random ( in : 1 ... 100 ) } func getRandomSuccess () -> Bool { Bool . random () } Both Int and Bool conform to a protocol called Equatable — which means they can be compared using == . So you can do this: print ( getRandomJutsu () == getRandomJutsu ()) That works fine, comparing two random integers. Now, since both return types conform to Equatable , you might think: what if we simplify both functions to return Equatable instead of their specific types? The Thing That Doesn't Work func getRandomJutsu () -> Equatable { // ❌ Int . random ( in : 1 ... 100 ) } func getRandomSuccess () -> Equatable { // ❌ Bool . random () } Swift refuses this with an error message so confusing it might as well be written in ancient runes: "protocol 'Equatable' can only be used as a generic constraint because it has Self or associated type requirements." Here's the actual problem in plain English: if both functions return Equatable , Swift loses track of what specific type is coming back. And if it doesn't know the specific type, it can't know whether two Equatable things can actually be compared to each other. Think about it: an Int and a Bool both conform to Equatable , but you can't compare them with == . That doesn't make sense. Swift isn't going to let y

本文内容来源于互联网,版权归原作者所有
查看原文