Anupam Mishra
Anupam Mishra

Reputation: 3588

Swift 2.0 compiler error @"Use of unresolved identifier"

I have written a program to find the greatest number using Xcode 7.0 playground in swift 2.0 which is

var arrofNumbare:Array = [1065782,4234,234,23,234,234,23,443,3978909,234000990];
var n:Int = 0
var greatestnumbar : Int = arrofNumbare[0]

while (n < arrofNumbare.count - 1)
{
   greatestnumbar = greatest(greatestnumbar, b:arrofNumbare[n+1])
    n++;
}

print("\(greatestnumbar)")

func greatest(a:Int , b:Int) -> Int
{
    if(a > b)
    {
    return a
    }
    else
    {
    return b
    }
}

everything is working proper but geeting following error while calling method enter image description here

Upvotes: 0

Views: 1635

Answers (1)

Abizern
Abizern

Reputation: 150615

Playgrounds run the code written in them sequentially.

The trouble you are having is that you have defined a function after the place where it was used.

If you move your function to above where it is called, then the error goes away.

var arrofNumbare:Array = [1065782, 4234, 234, 23, 234, 234, 23, 443, 3978909, 234000990];
var n: Int = 0
var greatestnumbar : Int = arrofNumbare[0]

func greatest(a:Int , b:Int) -> Int
{
    if(a > b)
    {
        return a
    }
    else
    {
        return b
    }
}

while (n < arrofNumbare.count - 1)
{
    greatestnumbar = greatest(greatestnumbar, b:arrofNumbare[n+1])
    n++;
}

print("\(greatestnumbar)")

Edited to add

Although not part of your question, here is a better way of doing what you want in Swift; using the reduce function

let array: [Int] = [1065782, 4234, 234, 23, 234, 234, 23, 443, 3978909, 234000990]
let maximumValue = array.reduce(Int.min) { (accumulator, value) -> Int in
    return max(accumulator, value)
}

the reduce function takes an initial value in an accumulator and and a closure that applies to this accumulator value and the next value in the array. After running this block on each element of the array, the accumulator value is returned. In the closure above I am just putting storing the larger of the accumulator and the next value into this accumulator.

This is a much clearer way of getting the maximum value.

It's also easier to reason about what your code is doing, because the mechanics of iterating through the array and updating the initial value is all taken care of. You can see that in your attempt, most of the code is related to iterating through the array.

Upvotes: 2

Related Questions