Reputation: 1076
I'm kinda new to Swift and I was wondering how do I make a function accept an array that contains all kinds of variables types. I want the function to just accept 'Array' without a specific type but it throws an error. Here's my code:
func length(arry arry: Array)
{
}
I know I have to put a <> after the Array but I need the function to universally accept all arrays.
EDITED: Whenever I add an extension I get these ridiculous errors. My code is:
//: Playground - noun: a place where people can play
import UIKit
extension Array {
var length: Int {
return self.count
}
}
var arrY = ["Hello", 0]
for(var i = 0; i < length(arry: arrY); i++)
{
print(arrY[i]);
}
arrY.append(28);
var h = arrY.removeAtIndex(0);
print(h);
I get errors saying: 1 On line ten Extensions may not contain stored properties 2 On line eleven Expected Declaration 3 On line eighteen Expected Declaration Thanks,
Jack
Upvotes: 3
Views: 182
Reputation: 70098
If you're used to .length
then make an extension to Array with a length
property:
extension Array {
var length: Int {
return self.count
}
}
Then you can call it on arrays like you're used to:
["a", "b"].length // 2
[0, 1].length // 2
Upvotes: 1
Reputation: 5113
If you want, you can write a generic function:
func length<T>(arry arry: Array<T>)
{
}
In Swift, Apple introduced the concept of Generics
which you can also now find it on Xcode 7 and Objective-C. This feature allows you to define the type of each element in the Array or the collection class that you're using. You can define a generic class or a generic method like the sample given. This feature gives you the ability of writing your code in a way that it can work safely with different types, while taking advantage of being type-safe. For example, in the sample that I gave, it's saying that length
is a generic method which takes an Array of type T
as input. Writing a method like this, allows you to write one method which is capable of accepting arrays of different types. For example, following sample code, is showing that you can use the same method for both array of Int
and array of Double
:
var arr = [13, 23, 32]
var arr2 = [12.3, 23.5, 13.14, 2.75]
var arr3 = ["foo", "boo"]
length(arr)
length(arr)
length(arr)
For more information on Generics you can check online documents at this Link, and/or watch Swift introduction videos for WWDC 2014, and/or reading generic section of The Swift Programming Language
Upvotes: 5
Reputation: 7906
Using a generic function is the better answer. But you could also use [Any]
as a parameter for this function.
func length(array: [Any])->Int{
return array.count
}
Upvotes: 1