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

如何使包中Swift枚举的初始化方法变为公开可访问?

问题原因

Swift 中,public 枚举的成员(case)默认访问级别是 internal。即便你在扩展中声明了 public 初始化方法,由于初始化方法内部需要访问这些 internal 的 case,编译器会自动将初始化方法的实际访问级别降级为 internal,导致外部模块无法访问该初始化器,从而抛出错误。

解决方法

显式将枚举的所有 case 声明为 public,确保初始化方法可以在外部模块正常访问这些 case:

public enum DataToValidate {
    public case object(JSONObject)
    public case array(JSONArray)
    public case string(String)
    public case number(Double)
}

extension DataToValidate {
    public init(associatedValue: Any) {
        switch associatedValue {
        case let intValue as Int:
            self = .number(Double(intValue))
        case let floatValue as Float:
            self = .number(Double(floatValue))
        case let doubleValue as Double:
            self = .number(doubleValue)
        case let stringValue as String:
            self = .string(stringValue)
        case let jsonObj as JSONObject:
            self = .object(jsonObj)
        case let jsonArr as JSONArray:
            self = .array(jsonArr)
        default:
            fatalError("Unrecognized type!")
        }
    }
}

同时优化了初始化方法中的强制解包逻辑,用 let ... as 的形式更安全简洁,避免不必要的强制转换操作。

内容的提问来源于stack exchange,提问作者user19549035

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:05:23