I have an NSMutableArray that contains String values. I have a String variable and I want to check if it is contained in the array or not.
I tried using .contains() with String but it say:
Cannot convert value of type String to expected argument type...
var mutableArray = NSMutableArray() // ["abc", "123"]
var string = "abc"
mutableArray.contains("abc") { // above error in this line
}
Multiple ways to check element existence in NSMutableArray. i.e
if mutableArray.contains("abc")
print("found")
else
print("not found")
or
if contains(mutableArray, "abc")
print("found")
or
if mutableArray.indexOfObject("abc") != NSNotFound
print("found")
If we want to check existence of element according of version of
swift
Swift1
if let index = find(mutableArray, "abc")
print(index)
Swift 2
if let index = mutableArray.indexOf("abc")
print(index)
I do still not understand why you cannot use a native Swift array, but okay.
Two possible solutions are to either use
let contains = mutableArray.contains { $0 as? String == "abc" }
or
let contains = mutableArray.containsObject("abc")
or
let contains = mutableArray.indexOfObject("abc") != NSNotFound
If you would use a native array you could simply do
var array = ["123", "abc"]
let contains = array.contains("abc")
Related
I have array:
let array = ["", "Therapeutic Dentistry","Surgical Dentistry","Orthopedic Dentistry","Orthodontics","Genaral Medical Questions","Children Therapeutic Dentistry","Children Surgical Dentistry"]
And i want get firs one, it's empty, how i can get this element from array?
Arrays have a first property which gives you the first element if it exists.
if let firstElement = array.first {
print(firstElement)
}
If you want the first element that is not an empty string then you can use the first(where:)
if let firstElement = arr.first(where: { $0 != "" }) {
print(firstElement)
}
Edit:
Question title was "iOS How get first element from array Swift" in the beginning which is why the answer has two parts.
let firstElement = array.first ?? DefaultValue
It means
let firstElement = array.first != nil ? array.first! : DefaultValue
DefaultValue is anything you defined.
Filter the array by removing "" values and get the first element.
array = array.filter({ $0 != "" })
if let first = array.first{
print(first)
}
I've been away for a while from swift development. And today I got bug report from my client on my old project. The thing is I used to access value from my dictionary with ease just like dictionary[key] then I already got the value, but today I got below error by doing that:
Type 'NSFastEnumerationIterator.Element' (aka 'Any') has no subscript members
and here is my code:
var rollStatusArray = NSMutableArray()
for statusDict in rollStatusArray{
if statusId == "\(statusDict["mark_status_id"]!!)"{
return "\(statusDict["mark_status_name"]!!)"
}
}
How can I access dictionary value on swift 3?
In Swift's use native type Array/[] instead of NS(Mutable)Array.
if let dicArray = rollStatusArray.objectEnumerator().allObjects as? [[String:Any]] {
for statusDict in dicArray {
//Here compiler know type of statusDict is [String:Any]
if let status_id = statusDict["mark_status_id"] as? String, status_id == statusId {
return "\(statusDict["mark_status_name"]!)"
}
}
}
Note I'm force wrapping the mark_status_name value you can use Nil coalescing operator to return empty string to remove force wrapping.
You need to tell compiler the type of your statusDict this way:
for statusDict in rollStatusArray {
if let obj = statusDict as? [String: AnyObject] {
let statusIdFromDict = obj["mark_status_id"] as? String ?? ""
if statusId == statusIdFromDict {
return statusIdFromDict
}
}
}
Using Swift 3, you can access the dictionary value the following way:
var rollStatusArray = NSMutableArray()
for statusDict in rollStatusArray{
if statusId == "\((statusDict as! NSDictionary)["mark_status_id"]!)"{
return "\((statusDict as! NSDictionary)["mark_status_name"]!)"
}
}
my output is coming like "Optional(\"A\") but I want only string "A". I have to apply filter on my array by using this character.
let char = selectedSection.characters.last
let str = String(char)
let array = result?.objectForKey("GetClassPeriodList") as! NSArray
let filtered = array.filter {
return ($0["Section_Code"] as! String) == str
}
print(filtered)
As #martin-r says, last gives you an optional because you can not be certain that when you ask for the last character of a collection, you actually end out with a character, what if the collection was empty for instance?
What you can do is unwrap it using if let, so you could write:
if let char = selectedSection.characters.last {
let str = String(char)
let array = result?.objectForKey("GetClassPeriodList") as! NSArray
let filtered = array.filter {
return ($0["Section_Code"] as! String) == str
}
print(filtered)
}
And then you know for certain that your char contains a value which you can continue to work with.
You can read more about optionals here
Hope that helps you.
if we have an array that contain strings for example {"houssam","hassan","taleb"}
and we have a string = "ss"
I need to return an array that return the string which contain ss, so in this case we have {"houssam","hassan"}
What is the best method to do that?
Thanks,
You can try this:
let string = "ss"
let array = ["houssam","hassan","taleb"]
let filtered = array.filter() { $0.containsString(string) }
let filterUsers:[String] = []
let users = [String] = ["houssam","hassan","taleb"]
let searchString = "ss"
filteredUsers = users.filter({( user: String) -> Bool in
let stringMatch = user.rangeOfString(searchString)
return stringMatch != nil
})
We filter the array of users and check to see if and where it contains "ss". It adds everything to the array where it found "ss" at least once.
This is my demo.
var arr: Array = ["loveyou","loveher","hateyou"]
var Newarr = arr.filter({ $0.containsString("love")})
print(Newarr)
I have a function that loops through an array that contains either Strings or Dictionaries and sets values for a new Dictionary of type [String:AnyObject], using values from the original array as keys. sections is an array of custom Section objects and its method getValue always returns a String.
func getSectionVariables() -> [String:AnyObject] {
var variables = [String:AnyObject]()
for section in sections {
if let name = section.name as? String {
variables[name] = section.getValue()
} else if let name = section.name as? [String:String] {
for (k, v) in name {
if variables[k] == nil {
variables[k] = [String:String]()
}
if var dict = variables[k] as? [String:String] {
dict[v] = section.getValue() //This works, but of course copies variables by value and doesn't set variables[k]
}
(variables[k] as? [String:String])![v] = section.getValue() //Can't get this line to compile
}
}
}
return variables
}
If I try to cast variables[k] as a [String:String], the compiler insists that String is not convertible to DictionaryIndex<String, AnyObject>. I'm not sure why downcasting isn't working and why the compiler thinks I'm trying to use the alternate dictionary subscript syntax.
Note that this project is in Swift 1.1.
The general problem is that a "cast expression" does not yield an "l-value" and therefore cannot be assigned to. For example, consider the following simplified version of the code:
var x = "initial"
var y : AnyObject? = x
(y as? String) = "change"
You will get an error on the last line, because you cannot assign to a "cast expression".