xxtmanxx
xxtmanxx

Reputation: 209

How do I access a variable declared in a function?

I can currently get rid of repeating objects in an array, but I want to call that array in the indexPath.row method, but I get the error that the variable is not defined since it is declared in a function. I tried instantiating as a nil globally, but that does not get rid of the repeating objects.

Var myVar = [<the T type>]()
uniq(<some source>, uniqueTitle: &myVar)

func uniq<S : SequenceType, T : Hashable where S.Generator.Element == T>(source: S) -> [T] {
            var buffer = [T]()
            var added = Set<T>()
            for elem in source {
                if !added.contains(elem) {
                    buffer.append(elem)
                    added.insert(elem)

                }
            }
            return buffer
        }
        //titleatcell is an array with repeating objects.
        titleatcell.append(title!)
        var uniqueTitle = uniq(titleatcell)
        uniqueTitle.append(title!)
        print(uniqueTitle)

     //return count of objects in array
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = table.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) 

    //Error: uniqueTitle is not declared. 
    cell.textLabel?.text = uniqueTitle[indexPath.row]
    return cell
}

Upvotes: 0

Views: 92

Answers (3)

Aidan Gomez
Aidan Gomez

Reputation: 8627

You can either pass uniqueTitle as an inout parameter to uniq, so you can set it within the uniq function. Or you can return uniqueTitle from uniq and then pass it to your second function.

For example:

Your function signature for uniq may be

func uniq<S : SequenceType, T : Hashable where S.Generator.Element == T>(source: S, inout uniqueTitle: [T]) -> [T]

And then you can pass in a globally defined variable like:

Var myVar = [<the T type>]()
uniq(<some source>, uniqueTitle: &myVar)

Now you can access myVar anywhere inside the same scope.

Upvotes: 1

Cody Weaver
Cody Weaver

Reputation: 4886

Seems like your messing with a UITableView and probably UITableViewDelegate all within a UIViewController. You could just make it a variable of your UIViewController class. Then it would be accessible from any function within the class.

Upvotes: 0

Abhinav
Abhinav

Reputation: 38142

How do I access a variable declared in a function?

There is no way you can do this. A variable declared locally inside a function is not known to outside world.

What you are looking for is pretty straightforward. Create a function that accepts an array and returns back the massaged array based on your business rules (after removing duplicates).

Upvotes: 1

Related Questions