简体   繁体   中英

Swift 2: Function counting occurrence in string not working

I'm trying to learn Swift 2 and count frequency of G's and C's in the input string .

I'm not getting any counts in my for-loop on the string. Xcode suggests I use let instead of var since for gc_count since it is not updating (which should not be the case!).

I'm also getting this error at my return statement:

Binary operator '/' cannot be applied to operands of type 'Double' and 'Float'

Tried Swift 2 - Search in string and sum the numbers

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

    var length: Float = Float(SEQ.characters.count)

    return gc_count/length
}

let query_seq = "ATGGGGCTTTTGA"
GC(query_seq)

If I did this in Python, I would simply:

def GC(input_seq):
    SEQ = input_seq.upper()
    gc_count = 0.0
    for nt in SEQ:
        if (nt == "G") or (nt == "C"):
            gc_count += 1
    return gc_count/len(SEQ)

Try replacing

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

with

if (nt == "G") {
    gc_count = gc_count + 1
}
if (nt == "C") {
    gc_count = gc_count + 1
}

If you write var gc_count inside the if body, you create a new local variable gc_count , which shadows the gc_count from the outter scope.

Also, use let for length, since you don't change it.

And since gc_count is Double , and your function returns Float and length is Float , you have to make some conversions somewhere. Or change some types.

With this considered and a few more improvements I got this:

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

    let length = Float(SEQ.characters.count)

    return Float(gc_count) / length
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM