Question
Can someone please explain the differences between these argument types? Furthermore, if possible please supply appropriate use-cases using cod
va_list
is a C type used for variable argument functions. You'll see this as a parameter in Objective-C code.
CVaListPointer
is the swift equivalent of a va_list
--wherever you see a function in Objective-C that takes va_list
as an argument, you'll pass in a CVaListPointer
in Swift.
objective-c: (NSPredicate *)predicateWithFormat:(NSString *)format arguments:(va_list)argList
swift: init(format format: String, arguments argList: CVaListPointer) -> NSPredicate
CVarArgType
is a protocol that defines what kind of types can be included in a CVaListPointer
, this includes all the primitives (Int
, Float
, UInt
, etc) as well as COpaquePointer
The utility function withVaList
takes a Swift array and transforms it into a CValListPointer
, which is then passed to a callback. Note that the array passed in must contain only CVarArgType
variables:
var format = "%@ != %@"
var args: [CVarArgType] = ["abc", "def"]
var s = withVaList(args) { (pointer: CVaListPointer) -> NSPredicate in
return NSPredicate(format: format, arguments: pointer)
}
Swift also defines its own varadic parameter T...
, which must be the last parameter in a function, it is passed into the function as [T]
and is used like so.
var arg1: String = "abc"
var arg2: String = "def"
NSPredicate(format: format, arg1, arg2)
Use Swift's built in varadic parameters T...
wherever possible. CValListPointer
should only be used when you need to interface with Objective C and C APIs that accept va_list
arguments.