如何使Swift的String类型符合CVarArgType协议?

sja*_*a26 5 swift

Swift协议定义为空:

public protocol CVarArgType {
}
Run Code Online (Sandbox Code Playgroud)

Apple文档页面未列出任何必需的方法:https : //developer.apple.com/library/ios/documentation/Swift/Reference/Swift_CVarArgType_Protocol/index.html

因此,我希望这可以工作:

extension String : CVarArgType {

}
Run Code Online (Sandbox Code Playgroud)

但出现构建错误:协议要求属性'_cVarArgEncoding'具有类型[[Int]'(Swift.CVarArgType)

鉴于协议定义为空,此要求从何而来?

如果我实现了计算属性,请继续前进:

extension String : CVarArgType {
    public var _cVarArgEncoding: [Int] {
        get {
            //What is expected to be returned here?
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

预期将以数组形式返回Int什么?

更新:为什么我需要这个?

我有一个名为Identifiable的协议,我的核心数据实体模型类符合该协议,我对此协议进行了扩展,并带有几个约束,以提供一个使用带有格式构造函数的NSPredicate中的id值的函数,该函数需要CVarArgType。

public protocol Identifiable {
    typealias IdentityType: CVarArgType, Hashable
    var id: IdentityType { get }
}

extension Identifiable where Self: Findable, Self: NSManagedObject {

    static public func find(id: IdentityType, context: NSManagedObjectContext) -> Self? {
        return find(NSPredicate(format: "id = %@", id), context: context)
    }

}

public extension Findable where Self: NSManagedObject {

    static public func find(predicate: NSPredicate?, context: NSManagedObjectContext) throws -> Self? {
        let fetchRequest = fetchRequestForEntity(inContext: context)
        fetchRequest.predicate = predicate
        fetchRequest.fetchLimit = 1
        return try context.executeFetchRequest(fetchRequest).first as? Self
    }

}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ord 5

我认为您不应该尝试使其他类型符合它们。在斯威夫特的源代码表示:

注意:该协议是公共的,但其要求是stdlib-private。那是因为有一些API在CVarArg实例上运行,但是不支持在标准库之外定义对CVarArg的一致性。

stdlib在许多方面都很特殊,并且比用户代码更深入地了解构建系统。这样的一个例子是,许多stdlib函数可以内联到您自己的代码中,而在其他情况下,当前无法跨模块边界实现。