how to change my String Value into Array by removing "()" - arrays

Let say I have values like this
Apple(100)
Orange(300)
Pineapple(10)
Grape(50)
Banana(1000)
What I want to do is to create an array which was like that to each string
["Apple","100"]
["Orange","300"]
What i tried was like that,but it doesn't meet my answer well enough
var myNewFruits = "Apple(200)"
var newStr = myNewFruits.componentsSeparatedByString("(")
The Output was
["Apple","200)"]
What i really want was
["Apple","200"]
Is there any help with Swift?Thank you.Because I am creating search with that,so,i really need it.

You can use a custom NSCharacterSet and get the first two elements from the returned array:
let myNewFruits = "Apple(200)"
let newStr = myNewFruits.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "()"))[0...1] // ["Apple", "200"]

You can do it this way:
func stringToArr(str: String) -> [String] {
var newArr = [String]()
var fullNameArr = split(str) {$0 == "("}
newArr.append(fullNameArr[0])
var last: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
newArr.append(last!.stringByReplacingOccurrencesOfString(")", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil))
return newArr
}
var string = "Apple(100)" //"Apple(100)"
let newArr = stringToArr(string) //["Apple", "100"]

Related

Swift all characters in texview in an array

I am trying to get all characters in an array, when user types something.
In my codes; when I type “hello” and print it, I get:
arrRegular: [“h”]
arrRegular: [“e”]
arrRegular: [“l”]
arrRegular: [“l”]
arrRegular: [“o”]
How can I make all characters in one array, like [“h”, “e”, “l”, “l”, “o”]
My codes:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
var arrRegular = [String]()
var arrBold = [String]()
var arrCombined = [String]()
if boldFont == false {
arrRegular.append(text)
} else {
arrBold.append(text)
}
arrCombined.append(contentsOf: arrRegular)
arrCombined.append(contentsOf: arrBold)
print(arrCombined)
return true
}
your var var arr = [String]() is local and is created every call of shouldChangeTextIn which is called every type of a character
You need to
let arr = Array(textView.text!)
or
let arr = textView.text.map { "\($0)" }
print(arr)
let text = textView.text ?? ""
let array = Array(text)

Swift: filter an array of Element1 [(String, Bool)] to return AND convert to an array of Element2 [String]?

I have an array of [(userID: String, friendBool: Bool)] that I want to filter AND convert to an array of userID's only [String] (removing the friendBool and therefore changing the element). Is there a function in Swift for doing this?
Currently, I am filtering on the array and then using a for loop on the filtered array [(userID: String, friendBool: Bool)] to convert it to an array of [String]. Is there a better way to do this?
Current Code:
let friendArray = [(userID: String, friendBool: Bool)]()
let excludeUsers = [String]()
//Updates with user actions
var userArrayForTableView = [String]()
//Filter friendArray
let newArray = friendArray.filter { (existingFriend) -> Bool in
return !excludeUsers.contains(existingFriend.userID)
}
//Convert array fro [(userID: String, friendBool: Bool)] to [String]
for existingFriend in newArray {
userArrayForTableView.append(existingFriend.userID)
}
What I'm trying to do:
//Loaded on ViewDidLoad
let friendArray = [(userID: String, friendBool: Bool)]()
let excludeUsers = [String]()
//Updates with user actions
var userArrayForTableView = [String]()
//Filter friendArray
/*
Below fitler returns an array of [(userID: String, friendBool: Bool)]...
but I want a filter to return an array of [String] for just userIDs
*/
let newArray = friendArray.filter { (existingFriend) -> Bool in
return !excludeUsers.contains(existingFriend.userID)
}
//ERROR HERE because 'newArray' is not [String]
userArrayForTableView.append(contentsOf: newArray)
What about using compactMap()?
In a certain way, it can be understood as a filter() (that you are already using) + map() (which is the loop for existingFriend in newArray in the first solution)
let userArrayForTableView = friendArray.compactMap({ (existingFriend) in
if excludeUsers.contains($0.userID) {
return nil
} else {
return existingFriend.id
}
})
In a shorter way:
let userArrayForTableView = friendArray.compactMap({ excludeUsers.contains($0.userID) ? nil : $0.userID })

JSON To Array in Swift

I'm Using Swift2.0+, SwiftyJSON, Alamofire
I Got the Value let stringJSON:JSON = ["a1","a2","a3"] from Server
But If I Check stringJSON[0],Then it's null
When I debugPrint(stringJSON), Then it's ["a1","a2","a3"]
How Can I got the value stringJSON[0] //"a1" ?
Do I Have To Convert From JSON To Another?
The correct syntax is
let stringJSON:JSON = ["a1","a2","a3"]
if let firstValue = stringJSON.array?.first {
print(firstValue) // a1
}
Update
Since the value actually contains this string "[\"a1\/a1\",\"a2\/a2\",\"a3\"]" and you cannot fix this on the server side here it is a workaround.
if let words = stringJSON.string?.characters.dropFirst().dropLast().split(",").map(String.init) {
let word = String(words[0].characters.dropFirst().dropLast())
print(word) // a1
}
if let x = stringJSON[0].string{
print(x)
}
Since the server is not returning an Array, but a String, you need to convert that into an Array of Strings like this:
let string = stringJSON.string
let array = string.stringByReplacingOccurrencesOfString("[", withString: "")
.stringByReplacingOccurrencesOfString("]", withString: "")
.stringByReplacingOccurrencesOfString("\"", withString: "")
.componentsSeparatedByString(",")
stringJSONIf it is a string type, you can like this to solve:
extension String {
var parseJSONString: AnyObject? {
var any: AnyObject?
let data = self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
do{
any = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)
}catch let error as NSError{
print("error: \(error)")
}
return any
}
and use it like this:
let strArr = stringJSON.stringvalue.parseJSONString as! Array<String>

Swift: Get multiple array values like "x"

For example, I have an array like var myArray = ['player_static.png', 'player_run0.png', 'player_run1.png', 'player_run2.png', 'player_jump0.png', 'player_jump1.png']
Is there any simple way to get only the "player_runX.png" images?
You can use filter to get all elements that hasPrefix("player_run"):
let myArray = ["player_static.png", "player_run0.png", "player_run1.png", "player_run2.png", "player_jump0.png", "player_jump1.png"]
let playerRuns = myArray.filter{$0.hasPrefix("player_run")}
print(playerRuns) //["player_run0.png", "player_run1.png", "player_run2.png"]
One way to do this would be to iterate over the array and retrieve the elements that match the pattern. A very quick sample would be something like this:
var myArray = ["player_static.png", "player_run0.png", "player_run1.png", "player_run2.png", "player_jump0.png", "player_jump1.png"]
func getSubArray(array:[String],prefix:String) -> [String]
{
var newArray = [String]()
for img in array
{
if img.substringToIndex(img.startIndex.advancedBy(prefix.characters.count)) == prefix
{
newArray.append(img)
}
}
return newArray
}
var test = getSubArray(myArray, prefix: "player_run")

How to convert from a Swift String Set to an Array

I am trying to create an array of words from a string object retrieved from Parse. The object retrieved looks like this:
Then this line of code gives this.
let joinedWords = object["Words"] as! String
How do I convert joinedWords to an Array?
If you don't care about the order, you can use flatMap on the set:
var mySet = Set<String>()
for index in 1...5 {
mySet.insert("testwords\(index)")
}
let myArray = mySet.flatMap { $0 }
print(myArray) // "["testwords5", "testwords3", "testwords4", "testwords2", "testwords1"]"
If you want the list sorted alphabetically, you can make your array a var and use sortInPlace()
var myArray = mySet.flatMap { $0 }
myArray.sortInPlace()
print(myArray) // "["testwords1", "testwords2", "testwords3", "testwords4", "testwords5"]"
If object["Words"] is AnyObject, you will have to unwrap it.
if let joinedWordsSet = object["Words"] as? Set<String> {
var joinedWordsArray = joinedWordsSet.flatMap { $0 }
myArray.sortInPlace()
print(myArray)
}
Swift 3 note: sortInPlace() has been renamed sort().
Many thanks to #JAL for so much time on chat to solve this one. This is what we came up with. Its a bodge and no doubt there is a better way!
When uploading to Parse save the set as an array.
let wordsSet = (wordList?.words?.valueForKey("wordName"))! as! NSSet
let wordsArray = Array(wordsSet)
Then it saves to Parse - looking like a set, not an array or a dictionary.
let parseWordList = PFObject(className: "WordList")
parseWordList.setObject("\(wordsArray)", forKey: "Words")
parseWordList.saveInBackgroundWithBlock { (succeeded, error) -> Void in
if succeeded {
// Do something
} else {
print("Error: \(error) \(error?.userInfo)")
}
}
Then you can drop the [ ] off the string when its downloaded from Parse, and remove the , and add some "" and voila, there is an array that can be used e.g. to add to CoreData.
var joinedWords = object["Words"] as! String
joinedWords = String(joinedWords.characters.dropFirst())
joinedWords = String(joinedWords.characters.dropLast())
let joinedWordsArray = joinedWords.characters.split() {$0 == ","}.map{ String($0) } // Thanks #JAL!

Resources