Search the index of an String in Array using Swift - arrays

A simple question but a big problem with the Apple Watch.
I am searching the index of an element in an Array. But the code gives me nil.
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
let temperatur = context as! String
let SliderData = ["off", "comfort", "eco","5.0", "5.5", "6.0", "6.5"]
println(toString(temperatur.dynamicType))
println(find(SliderData, "\(temperatur)") )
}

The array does not contain the string contained in the variable "temperatur" which is why you are not getting an index back.
If the value is already a string then you don't need to use "\(temperatur)" You can use this line instead:
println(find(SliderData, temperatur) )

You're searching for the string "temperatur" – which is obviously not in the array – rather than for the content of the variable temperatur
println(find(SliderData, temperatur) )

Related

Access a value in a dictionary using an int variable in Swift

I'm developing an iOS app and I want to access a specific value in a Dictionary using Array().
My dictionary contains an array, which contains structs.
let array = [(key: "S", value: [Thunderbolt.repoStruct(repoName: "Semiak Repo", repoURL: "https://repo.semiak.dev", icon: Optional("iconRound"))]), (key: "T", value: [Thunderbolt.repoStruct(repoName: "Thunderbolt iOS Utilities", repoURL: "https://repo.thunderbolt.semiak.dev", icon: Optional("iconRound"))])]
I'm making an UITableView with the array: the section name is the key value, the cell title is the repoStruct.repoName value, and the same with the following values.
To access repoName I'd use Array(array)[0].1[0].repoName.
The problem is that I do not know the exact location I want to access, instead, I use indexPath to know which value I need:
Array(array)[indexPath.section].indexPath.row[0].repoName
This should return me the repoName of the cell, but instead gives me the following error: Value of tuple type '(key: String, value: [repoStruct])' has no member 'indexPath'
I also tried using:
let row = indexPath.row
Array(array)[indexPath.section].row[0].repoName
but it gives me the same error: Value of tuple type '(key: String, value: [repoStruct])' has no member 'row'
I do not know why Array(array)[0].1 works and returns me the value, but Array(array)[indexPath.section].row doesn't. It is doing the same: accessing a value using the position, which is an int, such as indexPath.
How could I accomplish this?
Thanks in advance.
You are strongly discouraged from using tuples in a data source array. Replace the tuple with an extra struct
struct Section {
let name : String
let items : [Thunderbolt.repoStruct]
}
let array = [Section(name: "S", items: [Thunderbolt.repoStruct(repoName: "Semiak Repo", repoURL: "https://repo.semiak.dev", icon: Optional("iconRound"))],
Section(name: "T", items: [Thunderbolt.repoStruct(repoName: "Thunderbolt iOS Utilities", repoURL: "https://repo.thunderbolt.semiak.dev", icon: Optional("iconRound"))]]
and get an item at index path
let section = array[indexPath.section]
let item = section.items[indexPath.row]
let name = item.repoName
First of all, your array is already an array, so there's no need to say Array(array) - simply array will suffice, although generic names like this should be avoided.
I do not know why array[0].1[0] works
Let's pick this apart - your're accessing the first element in array via [0] and within that, the second element of the tuple .1, and lastly the first element of that valuearray. You could use array[0].value[0] for the same effect and make the code more readable.
but array[indexPath.section].row doesn't
That's because your array does not contain anything called row.
Use array[indexPath.section].value[indexPath.row].repoName instead.
Please try this code.
let dictData = arr[indexpath.section] //Element of section
let value = dictData["value"] //Value added in value in The element
let name = value[indexpath.row].reponame //Gives you name

Removing object from Array

How can you remove a specific object from an Array of string.
array = ["mac","iPhone","iPad"]
Is there a method to delete a specific string in the array, like for example i wanted to remove "iPhone", without using removeAtIndex(1)
Use filter for that purpose
var array = ["mac","iPhone","iPad"]
array = array.filter() { $0 != "mac" }
print(array) // will print ["iPhone", "iPad"]

PFObject Array Sort

I'm using Parse and I have an array of PFObjects called "scorecardData". Each PFObject has a "score" property that is of type Int. I'm trying to sort my array by "score" but I'm getting the following error: "Binary operator '<' cannot be applied to two 'AnyObject?' operands". I'm not sure what I'm doing wrong here. I also tried down casting the objectForKey("score") as! Int but its not letting me do this. Any suggestions? Thanks in advance.
var scorecardData = [PFObject]()
scorecardData.sortInPlace({$0.objectForKey("score") < $1.objectForKey("score")})
You declared scorecardData variable as Array of PFObject. Why are you trying access PFObject property using objectForKey: reserved? Anyway I am not parse expert. But if you declared your array as [PFObject] you can use:
scorecardData.sortInPlace({$0.score < $1.score})
But this won't work unless you subclass PFObject for a more native object-oriented class structure. If you do that remember also to specify:
var scorecardData = [YOUR_NEW_CLASS]()
I strongly recommend subclassing PFObject to make use of all swift type-safe goodies.
But if you want to keep your data structure you can use:
scorecardData.sortInPlace({($0["score"] as! Int) < ($1["score"] as! Int)})
Keep in mind that it's dangerous, and in future avoid it.
If you want to Sort your array of PFOject... You can do this
extension Array where Element:PFObject {
func sort() -> [PFObject] {
return sort { (first, second) -> Bool in
let firstDate = first.objectForKey("time") as! NSDate//objectForKey(Constants.Parse.Fields.User.fullName) as? String
let secondDate = second.objectForKey("time") as! NSDate//objectForKey(Constants.Parse.Fields.User.fullName) as? String
return firstDate.compare(secondDate) == .OrderedAscending
}
}
}
Have you tried doing this?
var query = PFQuery(className:"ScoreCard")
// Sorts the results in ascending order by the score field
query.orderByDescending("score")
query.findObjectsInBackgroundWithBlock {

Append unique values to an array in swift

I haven't found anything on that in Swift. Have found how to find unique values on an array, but not this. Sorry if it sounds quite basic...
But I have the following array
var selectedValues = [String]()
And the following value that comes from a Parse query
var objectToAppend = object.objectForKey("description")! as! String
this is how I'am doing it at the moment.
self.selectedHobbies.append(objectToAppend)
But because the query happens repeated times, it ends up appending repeated values. It works, but I just want to not waste memory and only keep unique values.
Any ideas on how to solve that in swift?
You can use a Set which guarantees unique values.
var selectedValues = Set<String>()
// ...
selectedValues.insert(newString) // will do nothing if value exists
Of course, the elements of a Set are not ordered.
If you want to keep the order, just continue with the Array but check before you insert.
if !selectedValues.contains("Bar") { selectedValues.append("Bar") }
I guess that your problem was resolved but I add my answer for next developers who's facing same problem :)
My solution is to write an extension of Array to add elements from an array with a distinct way:
here the code :
extension Array{
public mutating func appendDistinct<S>(contentsOf newElements: S, where condition:#escaping (Element, Element) -> Bool) where S : Sequence, Element == S.Element {
newElements.forEach { (item) in
if !(self.contains(where: { (selfItem) -> Bool in
return !condition(selfItem, item)
})) {
self.append(item)
}
}
}
}
example:
var accounts: [Account]
let arrayToAppend: [Account]
accounts.appendDistinct(contentsOf: arrayToAppend, where: { (account1, account2) -> Bool in
return account1.number != account2.number
})

Convert [String]? to String in Swift

For my project, I extracted tweets from a CSV file in Swift. Problem is now all tweets are parsed as one element in an array, separated by ",".
let tweetsOfColumns = columns["tweet"]
let seperatedColumns = tweetsOfColumns.componentsSeparatedByString(",")
Error message: '[String]?' does not have a member named
'componentsSeparatedByString'.
I checked if tweetsOfColumns contains multiple elements, but it doesn't allow me to subscript with tweetsOfColumns[index].
Looking at the link you reference, columns["tweets"] is going to give you back an array of the values from the "tweets" column, so it's what you need already, there's no additional comma's to split things on, you just need:
let seperatedColumns = columns["tweet"]
to have an array containing the tweet column for each row.
When you try to get an element from a dictionary, like
columns["tweet"]
it will give you back an optional, because if there is nothing associated with the key, it gives you back nil (None), otherwise the value wrapped in an optional (Some(data)).
So you have to unwrap the optional for example:
columns["tweet"]!
You have to either use the optional ? to access the string:
let seperatedColumns = tweetsOfColumns?.componentsSeparatedByString(",")
But you should unwrap it:
if let unwrappedTweets = tweetsOfColumns?.componentsSeparatedByString(","){
let seperatedColumns = unwrappedTweets
}
The problem is probably that you'll get an optional back, which you have to unwrap. And the easiest and most elegant is to use the if-let unwrapper.
if let tweetsOfColumns = columns["tweet"] {
let seperatedColumns = tweetsOfColumns.componentsSeparatedByString(",")
// do something with the seperatedColumns
}
Based on David's question and the OP's response in the OP comments, you can use map on the Array returned by columns["tweet"]. Please post actual data/code in the future.
let columns = [
"tweet":["handleX,tag1,tag2,textA,textB",
"handleY,tag1,tag2,textC,textD"]]
var chunk = [[String]]()
if columns["tweet"] != nil {
chunk = columns["tweet"]!.map {
return $0.componentsSeparatedByString(",")
}
}

Resources