O.rka
O.rka

Reputation: 30677

Function not working in Swift 2. (Unresolved identifier for defined variable)

I'm trying to move learn Swift 2 coming from a background of Python. Started making a really simple function that counts the G's and C's. I'm getting Use of unresolved identifier 'SEQ' on the line var length: Float = Float(SEQ.characters.count)

What am I doing wrong? It's definitely defined in the beginning of the function?

Tried the following posts:

Swift Use of unresolved identifier 'UIApplicationStateInactive'

Swift - Use of unresolved identifier

func GC(input_seq: String) -> Float {
    let SEQ = input_seq.uppercaseString
    var counter = 0.0
    for nt in SEQ.characters {
        if (nt == "G") {
            var counter = counter + 1
        }
        if (nt == "C") {
            var counter = counter + 1
            }
        }
    }
    var length: Float = Float(SEQ.characters.count)

    return counter/length
}

let query_seq = "ATGGGGCTTTTGA"
GC(query_seq)

Upvotes: 0

Views: 1486

Answers (1)

Paul Ardeleanu
Paul Ardeleanu

Reputation: 6700

Couple of things you do wrong.

  1. You are creating a Double counter (not a Float as you probably intended): var counter = 0.0

You really need it as an integer since it's a counter. You can convert it to a Float later. var counter = 0 will create an Int variable

  1. you are creating a second and a third local variables in the if blocks:

    if (nt == "G") { var counter = counter + 1 }

I don't think you understand the basics and might be beneficial for you to start reading the Swift book from the beginning.

  1. This is really an improvement - you can use a shorthands:

counter = counter + 1 to counter += 1 or even counter++

Here is a working version of your code:

func GC(input_seq: String) -> Float {
    let SEQ = input_seq.uppercaseString
    var counter = 0
    for nt in SEQ.characters {
        if (nt == "G") {
            counter++
        }
        if (nt == "C") {
            counter++
        }
    }

    return Float(counter)/Float(SEQ.characters.count)
}

let query_seq = "ATGGGGCTTTTGA"
GC(query_seq)

Hope this helps.

Upvotes: 1

Related Questions