Variadic Parameters Accept Array
Inputs
One of the main underlying problems with variadic parameters in Swift, is the inability to pass them around in functions or call them within functions.¹
Here is an example of what Swift should offer:
protocol ShoppingListItem { }
enum Furniture : ShoppingListItem {
case Chair
case Sofa
case Bed
case Table
}
enum CableType : ShoppingListItem {
case MicroUSB
case Lightning
case USB_C
case HDMI
}
extension String : ShoppingListItem { }
typealias ShoppingList = [ShoppingListItem]
func compileShoppingList<Item: ShoppingListItem>(_ arrs: Array<Item>...) -> ShoppingList {
var returnArr = [ShoppingListItem]()
arrs.forEach { arr in
arr.forEach { item in
returnArr.append(item)
}
}
return returnArr
}
@discardableResult func makeShoppingList(with items: ShoppingList...) -> ShoppingList {
var count = 1
print("\nShopping List:", terminator: "\n\n")
items.forEach { list in
print("\tErrand #\(count):")
count += 1
list.enumerated().forEach { (index, item) in
print("\t\t\(index + 1). \(item)")
}
print("\n", terminator: "")
}
let shoppingList : ShoppingList = compileShoppingList(items)
//Above Error: In argument type '[ShoppingList]' (aka 'Array<Array<ShoppingListItem>>'), 'ShoppingList' (aka 'Array<ShoppingListItem>') does not conform to expected type 'ShoppingListItem'
return shoppingList
}
let groceryList : [String] = ["Eggs", "Apples", "Orange Juice", "Cookies"]
let furnitureList : [Furniture] = [.Chair, .Bed, .Sofa, .Table]
let dongleList : [CableType] = [.Lightning, .USB_C, .MicroUSB, .HDMI]
makeShoppingList(with: groceryList, furnitureList, dongleList)
/* Prints (If there is no error, which there is):
Shopping List:
Errand #1:
1. Eggs
2. Apples
3. Orange Juice
4. Cookies
Errand #2:
1. Chair
2. Bed
3. Sofa
4. Table
Errand #3:
1. Lightning
2. USB_C
3. MicroUSB
4. HDMI
*/
Main Problem
The main problem that this brings up is the inability to use methods/functions that have inputs of variadic parameters – for the most part¹ – within other methods/functions.
Proposed Solution
Variadic parameters should accept Array
(and maybe Set
) as a valid inputs, so to make variadic parameters easier to use and more passable between functions.
Footnotes:
¹. mainly passing parameters from the larger function to the function with a variadic parameter within it.