Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make Swift's String type conform to the CVarArgType protocol?

Tags:

swift

The Swift protocol definition is empty:

public protocol CVarArgType {
}

The Apple documentation page doesn't list any required methods: https://developer.apple.com/library/ios/documentation/Swift/Reference/Swift_CVarArgType_Protocol/index.html

So I would expect this to work:

extension String : CVarArgType {

}

but I get a build error: Protocol requires property '_cVarArgEncoding' with type '[Int]' (Swift.CVarArgType)

Where does this requirement come from, given that the protocol definition is empty?

Moving forward if I implement the computed property:

extension String : CVarArgType {
    public var _cVarArgEncoding: [Int] {
        get {
            //What is expected to be returned here?
        }
    }
}

What is expected to be returned as an array of Int?

Updated: Why do I need this?

I have a protocol named Identifiable that my Core Data entity model classes conform to, I have an extension to this protocol with a couple of constraints to provide a function that uses the id value in an NSPredicate with format constructor which requires the 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
    }

}
like image 646
sja26 Avatar asked Mar 14 '16 14:03

sja26


People also ask

What is string protocol?

A type that can represent a string as a collection of characters.

What is Cvararg in Swift?

A type whose instances can be encoded, and appropriately passed, as elements of a C va_list .


1 Answers

I don't think that you should be trying to conform other types to them. The Swift source code says:

Note: the protocol is public, but its requirement is stdlib-private. That's because there are APIs operating on CVarArg instances, but defining conformances to CVarArg outside of the standard library is not supported.

The stdlib is special in quite a few ways and hooks deeper into the build system than user code can. One example of this is that many stdlib functions can be inlined into your own code which is not currently possible across module boundaries in other cases.

like image 96
Joseph Lord Avatar answered Nov 15 '22 06:11

Joseph Lord