Neel Goswami
Neel Goswami

Reputation: 1

Can't compare string entered through terminal to another string in Swift

I am using the following code to implement basic dictionary using swift. However the compiler is not returning any values. I don't know what seems to be the problem. Need Help!

P.S I'm new to Swift.

import Foundation

var dic = ["Nil":"Neel Goswami","Kirana":"Kinara Shah","Sapre":"Rohan Sapre","JP":"Joy Patel","Shreya":"Shrey Bhat","Ali Bhai":"Aalisha Sheth","Gandhi":"Shlok Gandhi","Binti":"Biyanta Shah","Udgam":"Aayushi Shah"]

dic["Wary"] = "Aishwary Rawat"
dic["Sixer"] = "Ruchir Patel"
dic["Bhikhari"] = "Aabhas Singhal"

var str: String? = "Initial"

println("Enter the pet name: ")

str = NSString(data: NSFileHandle.fileHandleWithStandardInput().availableData, encoding:NSUTF8StringEncoding)

var st: String = str!

for (pet, act) in dic
{
    if (pet == st) {
        println("His/Her actual name is \(act)")
    }
}

Upvotes: 0

Views: 97

Answers (1)

Martin R
Martin R

Reputation: 539815

The problem is that the string from the user input contains a trailing newline character (\n). You can fix that by changing

var st: String = str!

to

var st = str!.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())

Alternatively, use

var st = str!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

which removes leading and trailing space characters as well.

Note that you could simplify your for-loop to a dictionary lookup:

if let act = dic[st] {
    println("His/Her actual name is \(act)")
}

Upvotes: 1

Related Questions