How to compare [String]? and String in Swift?
You can't compare a string with an optional array of strings, they have two different types: The equality operator ==
, as defined in the standard library, can't compare a string to an optional array of strings.
If you want to check if an optional array contains a string, then use the following:
let array: [String]? = ["hello", "world", "✋]
let result = array?.contains("hello")
result
would be an optional boolean that you may unwrap later.
String Comparison Not Working With Swift
Alright, I figured out what was happening. I appreciate everyone's help and the suggestions lead me down a path of trying some other options. What was happening is "courseFromRealm" was only taking on the last value in my previousCoursesFromRealm when using the for-in loop. This is why sometimes it worked and sometimes it didn't because if the course I selected was the last value in the for-in loop then my code appeared to work otherwise it didn't. So I got rid of the for-in loop and used the "contains" method on previousCoursesFromRealm to simply check if this course I was selecting was already in my list of previous courses. If it is then I display the alert message and if not then I add it to the list. Again, thanks for everyone's help! still a little new to programming and working though it.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if searchController.active {
let realm = try! Realm()
try! realm.write {
let addPreviousCourse = PreviousCourse()
addPreviousCourse.name = searchResults![indexPath.row].name
addPreviousCourse.city = searchResults![indexPath.row].city
addPreviousCourse.state = searchResults![indexPath.row].state
self.previousCourse = addPreviousCourse
if previousCoursesFromRealm.contains( { $0.name == previousCourse.name }) {
displayAlert("Whoops!", message: "This course already exists inside of your previous course list. Please choose a different course.", actionTitle: "OK")
} else {
realm.add(previousCourse)
searchController.active = false
}
}
if searchController.active == false {
coursesTableView.reloadData()
}
}
}
How to compare two strings ignoring case in Swift language?
Try this:
var a = "Cash"
var b = "cash"
let result: NSComparisonResult = a.compare(b, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil)
// You can also ignore last two parameters(thanks 0x7fffffff)
//let result: NSComparisonResult = a.compare(b, options: NSStringCompareOptions.CaseInsensitiveSearch)
result is type of NSComparisonResult enum:
enum NSComparisonResult : Int {
case OrderedAscending
case OrderedSame
case OrderedDescending
}
So you can use if statement:
if result == .OrderedSame {
println("equal")
} else {
println("not equal")
}
How to compare string in swift4
As the error states you cannot compare a String
(mycheck
) with an array of Any
(localMsg
), you must compare the string directly with something like
if let localMsg = oDict_Fail["message"] as? String, localMsg == mycheck {
NSLog("True")
} else {
NSLog("False")
}
Here we first try to access the oDict_Fail
dictionary with the key message
, if it exists try to cast it as a String
and if it is successful only then do the comparison, if any of this fails the else
branch will be executed.
You can read more about optional binding here.
Swift string comparison failing
Remove invisible chars as sugegsted by Martin :
String(tagChosen.text!).trimmingCharacters(in: .whitespacesAndNewlines) == String(row[self.tag])).trimmingCharacters(in: .whitespacesAndNewlines)
Related Topics
What Is the Reduce() Function Doing, in Swift
Convert a Swift Array of String to a to a C String Array Pointer
Can Associated Values and Raw Values Coexist in Swift Enumeration
Swift Generics: Requiring Addition and Multiplication Abilities of a Type
Using Function Parameter Names in Swift
Xcode 9 and Xcode 10 Giving Different Results, Even with Same Swift Version
Custom Segue Transition Animation
Is There a Difference Between Swift 2.0 Protocol Extensions and Java/C# Abstract Classes
What Does the Swiftui '@State' Keyword Do
Swift Spritekit Adding Button Programmatically
Finish Asynchronous Task in Firebase With Swift
Formatting Decimal Places with Unknown Number
How to Convert Timeinterval into Minutes, Seconds and Milliseconds in Swift
Download File from Server Using Swift