Swift的“Self”(大写S)和小写“self”是什么,有什么区别,如何用?

    科技2026-09-21  21

    Swift的“Self”(大写S)是什么,如何用?

    在Swift中,Self是指代类型,通常是当前上下文中的当前类型。正如小写字母self可以表示任何当前对象一样,大写字母Self也可以表示几乎任何当前类型。

    类和结构中的“Self”

    struct Dog { static func createDogs(count: Int, canTalk: Bool) -> [Self] { return (0..<count).map { _ in Dog(canTalk: canTalk) } } }

    上面代码中大写Self指代就是当前Dog类型

    协议和扩展extensions中的Self

    extension Numeric { func squared() -> Self { return self * self } } let number = 42 print(number.squared()) // 1764

    Self指的是符合Numeric协议的类型。在示例中,Self将是具体类型Int,因为42它是整数。如何squared()时是Double,Self会是Double。使用Self我们可以避免硬编码。

    extension Sequence where Element: Numeric { func squareAll() -> [Self.Element] { return map { $0 * $0 } } } print((0...10).squareAll()) // Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

    在Sequence协议中,Element是一个关联的类型。您可以将其视为协议的通用占位符。当协议用于具体类型(如)时Array,Element将是数组中各项的类型。

    加入我们一起学习SwiftUI

    QQ:3365059189 SwiftUI技术交流QQ群:518696470

    Processed: 0.013, SQL: 9