Swift: Convert String to NSMutableArray [duplicate] - ios

This question already has answers here:
Split a String into an array in Swift?
(40 answers)
Closed 6 years ago.
I want to convert following String to NSMuableArray.
var components: String = "library/book/science"
For example, I want to perform the following objective c code in Swift
NSArray *componentsArray = [#"library/book/science" componentsSeparatedByString:#"/"];
NSMutableArray *componentsMutableArray = [[NSMutableArray alloc] initWithArray:componentsArray];
[componentsMutableArray addObject:#"astronomy"];

Here is your working swift code:
var components: String = "library/bool/science"
let componentsArray = components.componentsSeparatedByString("/") //["library", "bool", "science"]
let componentsMutableArray = NSMutableArray(array: componentsArray) //["library", "bool", "science"]
componentsMutableArray.addObject("astronomy") //["library", "bool", "science", "astronomy"]

var components: String = "library/book/science"
var componentMutableArray = components.componentsSeparatedByString("/")
componentMutableArray.append("astronomy")

You need to use NSString in order to call the componentsSeparatedByString function that will split your text into an array based on the separator of your choice.
let theString = NSString(string: "library/book/science")
let components = theString.componentsSeparatedByString("/")

Related

How to extract phrase from string using Range? [duplicate]

This question already has answers here:
Finding index of character in Swift String
(33 answers)
Closed 6 years ago.
This sounds easy, but I am stumped. The syntax and functions of Range are very confusing to me.
I have a URL like this:
https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post
I need to extract the part #global-best-time-to-post, essentially the # to the end of the string.
urlString.rangeOfString("#") returns Range
Then I tried doing this assuming that calling advanceBy(100) would just go to the end of the string but instead it crashes.
hashtag = urlString.substringWithRange(range.startIndex...range.endIndex.advancedBy(100))
Easiest and best way to do this is use NSURL, I included how to do it with split and rangeOfString:
import Foundation
let urlString = "https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post"
// using NSURL - best option since it validates the URL
if let url = NSURL(string: urlString),
fragment = url.fragment {
print(fragment)
}
// output: "global-best-time-to-post"
// using split - pure Swift, no Foundation necessary
let split = urlString.characters.split("#")
if split.count > 1,
let fragment = split.last {
print(String(fragment))
}
// output: "global-best-time-to-post"
// using rangeofString - asked in the question
if let endOctothorpe = urlString.rangeOfString("#")?.endIndex {
// Note that I use the index of the end of the found Range
// and the index of the end of the urlString to form the
// Range of my string
let fragment = urlString[endOctothorpe..<urlString.endIndex]
print(fragment)
}
// output: "global-best-time-to-post"
You could also use substringFromIndex
let string = "https://github.com..."
if let range = string.rangeOfString("#") {
let substring = string.substringFromIndex(range.endIndex)
}
but I'd prefer the NSURL way.
use componentsSeparatedByString method
let url = "https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post"
let splitArray = url.componentsSeparatedByString("#")
your required last text phrase (without # char) will be at the last index of the splitArray , you can concatenate the # with your phrase
var myPhrase = "#\(splitArray[splitArray.count-1])"
print(myPhrase)

swift , sort nsmutableArray with objects [duplicate]

This question already has an answer here:
Sorting an array with instances of a custom class
(1 answer)
Closed 7 years ago.
i have nsmutablearray with objects
user_id , username , user_Last_Update_Info
and i want to sort this array by user_Last_Update_Info
how to do it ??
Try this:
arrayToSort.sortUsingComparator{
(obj1:AnyObject!, obj2:AnyObject!) -> NSComparisonResult in
var dateStr1 = obj1["user_Last_Update_Info"] as NSString
var date1: NSDate = dateFormatter.dateFromString(dateStr1)!
var dateStr2 = obj2["user_Last_Update_Info"] as NSString
var date2: NSDate = dateFormatter.dateFromString(dateStr2)!
return date2.compare(date1)
}
This should help:
// Example for Swift Array
myArray.sortInPlace {
obj1 , obj2 in
dic1.user_Last_Update_Info < dic2.user_Last_Update_Info
}
// Example for Swift NSMutableArray
// newArr is an optional [AnyObject], you should cast it to what you expect
let newArr = myArray.sortedArrayUsingDescriptors([NSSortDescriptor(key: "user_Last_Update_Info", ascending: true)])

How to get substring of String in Swift? [duplicate]

This question already has answers here:
How do you use String.substringWithRange? (or, how do Ranges work in Swift?)
(33 answers)
Closed 7 years ago.
If I want to get a value from the NSString "😃hello World😃", what should I use?
The return value I want is "hello World".
The smileys can be any string. so i need some regexp to this.
There's more than one way to do it.
First: String in Swift 1.2 is bridged to NSString properly so the answer could be : How to get substring of NSString?
Second: This answer will deal with emoticon characters too.
var s = "😃hello World😃"
let index = advance(s.startIndex, 1) // index is a String.Index to the 2nd glyph, “h”
let endIndex = advance(s.startIndex, 12)
let substring=s[index..<endIndex] // here you got "hello World"
if let emojiRange = s[index...s.endIndex].rangeOfString("😃") {
let substring2 = s[index..<emojiRange.startIndex] // here you get "hello World"
}

Concatination of strings in Swift [duplicate]

This question already has answers here:
How do I concatenate strings in Swift?
(21 answers)
Closed 7 years ago.
I would like to get final String like below:
var urlString = "http://testurl.com/contacts=["1111111","2222222"]"
There are three strings http://testurl.com/contacts= , 1111111 and 2222222
How to concatenate these strings in Swift
var str1 = "http://testurl.com/contacts="
var str2 = "1111111"
var str3 = "2222222"
var finalString = "\(str1)[\"\(str2)\",\"\(str3)\"]"

String to Double in XCode 6's Swift [duplicate]

This question already has answers here:
Swift - How to convert String to Double
(30 answers)
Closed 7 years ago.
How do I convert a string to double in Swift? I've tried string.doubleValue or string.bridgeToObjectiveC().doubleValue and none of it works. Any ideas?
You can create a read-only computed property string extension to help you convert your strings to double:
You can use NSNumberFormatter
extension String {
struct Number {
static let formatter = NSNumberFormatter()
}
var doubleValue: Double {
return Number.formatter.numberFromString(self)?.doubleValue ?? 0
}
}
or you can cast it to NSString and extract its doubleValue property:
extension String {
var ns: NSString {
return self
}
var doubleValue: Double {
return ns.doubleValue
}
}
"2.35".doubleValue + 3.3 // 5.65
According to Stanford CS193p course Winter 2015, the correct way to get a double from a String in Swift is to use NSNumberFormatter instead of NSString:
let decimalAsString = "123.45"
let decimalAsDouble = NSNumberFormatter().numberFromString(decimalAsString)!.doubleValue
If you want to be safe (regarding the optional unwrapping and the decimal separator), you'd use:
let decimalAsString = "123.45"
var formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US")
if let decimalAsDoubleUnwrapped = formatter.numberFromString(decimalAsString) {
decimalAsDouble = decimalAsDoubleUnwrapped.doubleValue
}
Safe unwrapping is particularly useful if you parse a XML or JSON file and you need to make sure you have a String that can be converted into a Double (the program will crash if you force-unwrap an optional that is actually nil).
/!\
EDIT: be careful, NSNumberFormatter works differently than NSString.
NSString allowed you to do things like : (dictionary[key] as NSString).doubleValue, provided that dictionary[key] used the '.' as decimal separator (like in "123.45").
But NSNumberFormatter(), by default, initializes an instance of NSNumberFormatter with your current system Locale!
Therefore, NSNumberFormatter().numberFromString(decimalAsString)!.doubleValue would work with 123.45 on a US device, but not on a French one for example!
If you are parsing a JSON file for example, and you know that values are stored using '.' as the decimal separator, you need to set the locale of your NSNumberFormatter instance accordingly:
var formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US")
then:
let decimalAsString = "123.45"
if let decimalAsDoubleUnwrapped = NSNumberFormatter().numberFromString(decimalAsString) {
decimalAsDouble = decimalAsDoubleUnwrapped.doubleValue
}
In that case, decimalAsDouble will correctly return 123.45 as a doubleValue.
But it would return nil if decimalAsString = "123,45".
Or if the NSLocale was set as "fr_FR".
On the other hand, a NSNumberFormatter using a NSLocale with fr_FR would work perfectly with "123,45", but return nil with "123.45".
I thought that was worth reminding.
I updated my answer accordingly.
EDIT : also, NSNumberFormatter wouldn't know what do with things like "+2.45%" or "0.1146"(you would have to define the properties of your NSNumberFormatter instance very precisely). NSString natively does.
you can always just cast from String to NSString like this
let str = "5"
let dbl = (str as NSString).doubleValue
Try this :
var a:Double=NSString(string: "232.3").doubleValue
Try this:
let str = "5"
let double = Double(str.toInt()!)
another way is:
let mySwiftString = "5"
var string = NSString(string: mySwiftString)
string.doubleValue
this latter one posted here:
Swift - How to convert String to Double

Resources