'String" is not convertible to '[(String)]' - string

I am trying to split a string returned from a URL by ", " but when I attempt
var tagArray = [String]()
if response.responseObject != nil {
let data = response.responseObject as NSData
let str = NSString(data: data, encoding: NSUTF8StringEncoding)!
self.tagArray = str.componentsSeparatedByString(", ") as String
println("response: \(self.tagArray)") //prints the HTML of the page
}
The line self.tagArray = str.componentsSeparatedByString(", ") as String throws the error "'String" is not convertible to '[(String)]'"
Anyone know how to properly split the string into the array?

The offending line is missing the [] in the cast -- you're casting to a String when you need to be casting to an array of Strings:
var tagArray = [String]()
if response.responseObject != nil {
let data = response.responseObject as NSData
let str = NSString(data: data, encoding: NSUTF8StringEncoding)!
self.tagArray = str.componentsSeparatedByString(", ") as [String]
println("response: \(self.tagArray)") //prints the HTML of the page
}

Related

get value of nested array alamofire swift 3

I need to get the nested array values, I need the user data and I need token data. I need this data because I need to initialize session variables to be able to use them in my application.
For example the user name, fotografia, managed to get the data rc and msg that are in the main array but I could not get the values ​​of nested arrays
["rc": 00,
"user": {
"__v" = 0;
deviceId = "";
email = "john#gmail.com";
fullName = "SMITH JOHN ";
lastName = "SMITH ";
modifiedAt = "2016-12-16T06:08:58.856Z";
name = "JOHN ";
photo = "";
provider = "";
"provider_id" = "";
status = 01;
tel = 3333333333;
typeUser = USER;
username = "john#gmail.com";
}, "token": {
"__v" = 0;
"_id" = 585384e3ccc4;
createdAt = "2016-12-16T08:10:03.407Z";
userId = 585384e3ccc4;
value = Z4WedlAzhdkap;
}, "msg": success]
#IBAction func btnLogin(_ sender: Any) {
let gsUtil=GSUtil()
let user = txtUser.text!
let password = txtPass.text!
let credentialData = "\(user):\(password)".data(using: String.Encoding.utf8)!
let base64Credentials = credentialData.base64EncodedString(options: [])
let headers = ["Authorization": "Basic \(base64Credentials)"]
Alamofire.request(gsUtil.getCompleteURI()+"user/auth/",
method: .post,
parameters: nil,
encoding: URLEncoding.default,
headers:headers)
.validate()
.responseJSON { response in
if response.result.value != nil{
let json = response.result.value as? [String: Any]
let rc=json?["rc"]
let msg=json?["msg"]
if rc as? String=="00"
{
self.showMessage(msg: msg as! String)
}
}else{
self.showMessage(msg: "Error en los datos")
}
}
}
I do not really get the problem. You already pretty much did what you need to do (only one step further):
I would start by getting rid of all the pesky optionals using a lot of if lets:
if let json = input as? [String: Any] {
let msg = json["msg"]
if let rc = json["rc"] as? String, rc == "00" {
self.showMessage(msg: msg as! String)
}
if let user = json["user"] as? [String : Any] {
print(user)
}
if let token = json["token"] as? [String : Any] {
print(token)
}
} else {
self.showMessage(msg: "Error en los datos")
}

Base64 encode decode for image URL in Swift 3

This is how I encoded:
let url:NSURL = NSURL(string : pictURL)!
let imageData : NSData = NSData.init(contentsOf: url as URL)!
let str64 = imageData.base64EncodedData(options: .lineLength64Characters)
// next line my code to save in core data just ignore it
The value for encoded data = 3286 bytes. I think it is wrong
let pictEncoded = person.value(forKeyPath: "pictureurl") as! String
if let imageData = Data(base64Encoded: pictEncoded, options: .ignoreUnknownCharacters),
let image = UIImage(data: imageData)
{
cell.imgView.image = image
}

How to split a string in Swift [duplicate]

This question already has answers here:
Split a String into an array in Swift?
(40 answers)
Closed 8 years ago.
let string = "hello hi"
var hello = ""
var hi = ""
I wan't to split my string so that the value of hello get "hello" and the value of hi get "hi"
Try this:
var myString: String = "hello hi";
var myStringArr = myString.componentsSeparatedByString(" ")
Where myString is the name of your string, and myStringArr contains the components separated by the space.
Then you can get the components as:
var hello: String = myStringArr [0]
var hi: String = myStringArr [1]
Doc: componentsSeparatedByString
EDIT: For Swift 3, the above will be:
var myStringArr = myString.components(separatedBy: " ")
Doc: components(separatedBy:)
Here are split that receives regex as well. You can define extension for future usage:
Swift 4
extension String {
func split(regex pattern: String) -> [String] {
guard let re = try? NSRegularExpression(pattern: pattern, options: [])
else { return [] }
let nsString = self as NSString // needed for range compatibility
let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
let modifiedString = re.stringByReplacingMatches(
in: self,
options: [],
range: NSRange(location: 0, length: nsString.length),
withTemplate: stop)
return modifiedString.components(separatedBy: stop)
}
}
Examples:
let string1 = "hello world"
string1.split(regex: " ") // ["hello", "world"]
let string2 = "hello world"
string2.split(regex: "[ ]+") // ["hello", "world"]
Swift 2.2
extension String {
func split(regex pattern: String) -> [String] {
guard let re = try? NSRegularExpression(pattern: pattern, options: [])
else { return [] }
let nsString = self as NSString // needed for range compatibility
let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
let modifiedString = re.stringByReplacingMatchesInString(
self,
options: [],
range: NSRange(location: 0, length: nsString.length),
withTemplate: stop)
return modifiedString.componentsSeparatedByString(stop)
}
}
Swift 2.0
extension String {
// java, javascript, PHP use 'split' name, why not in Swift? :)
func split(regex: String) -> Array<String> {
do{
let regEx = try NSRegularExpression(pattern: regex, options: NSRegularExpressionOptions())
let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
let nsString = self as NSString // needed for range compatibility
let modifiedString = regEx.stringByReplacingMatchesInString (self, options: NSMatchingOptions(), range: NSRange(location: 0, length: nsString.length), withTemplate:stop)
return modifiedString.componentsSeparatedByString(stop)
} catch {
return []
}
}
}
Swift 1.1
extension String {
// java, javascript, PHP use 'split' name, why not in Swift? :)
func split(splitter: String) -> Array<String> {
let regEx = NSRegularExpression(pattern: splitter, options: NSRegularExpressionOptions(), error: nil)
let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
let modifiedString = regEx.stringByReplacingMatchesInString (self, options: NSMatchingOptions(),
range: NSMakeRange(0, countElements(self)),
withTemplate:stop)
return modifiedString.componentsSeparatedByString(stop)
}
}
Examples:
let string1 = "hello world"
string1.split(" ") // ["hello", "world"]
let string2 = "hello world"
string2.split("[ ]+") // ["hello", "world"]

Convert Int to String in Swift

I'm trying to work out how to cast an Int into a String in Swift.
I figure out a workaround, using NSNumber but I'd love to figure out how to do it all in Swift.
let x : Int = 45
let xNSNumber = x as NSNumber
let xString : String = xNSNumber.stringValue
Converting Int to String:
let x : Int = 42
var myString = String(x)
And the other way around - converting String to Int:
let myString : String = "42"
let x: Int? = myString.toInt()
if (x != nil) {
// Successfully converted String to Int
}
Or if you're using Swift 2 or 3:
let x: Int? = Int(myString)
Check the Below Answer:
let x : Int = 45
var stringValue = "\(x)"
print(stringValue)
Here are 4 methods:
var x = 34
var s = String(x)
var ss = "\(x)"
var sss = toString(x)
var ssss = x.description
I can imagine that some people will have an issue with ss. But if you were looking to build a string containing other content then why not.
In Swift 3.0:
var value: Int = 10
var string = String(describing: value)
Swift 4:
let x:Int = 45
let str:String = String(describing: x)
Developer.Apple.com > String > init(describing:)
The String(describing:) initializer is the preferred way to convert an instance of any type to a string.
Custom String Convertible
Just for completeness, you can also use:
let x = 10.description
or any other value that supports a description.
Swift 4:
Trying to show the value in label without Optional() word.
here x is a Int value using.
let str:String = String(x ?? 0)
To save yourself time and hassle in the future you can make an Int extension. Typically I create a shared code file where I put extensions, enums, and other fun stuff. Here is what the extension code looks like:
extension Int
{
func toString() -> String
{
var myString = String(self)
return myString
}
}
Then later when you want to convert an int to a string you can just do something like:
var myNumber = 0
var myNumberAsString = myNumber.toString()
in swift 3.0 this is how we can convert Int to String and String to Int
//convert Integer to String in Swift 3.0
let theIntegerValue :Int = 123 // this can be var also
let theStringValue :String = String(theIntegerValue)
//convert String to Integere in Swift 3.0
let stringValue : String = "123"
let integerValue : Int = Int(stringValue)!
for whatever reason the accepted answer did not work for me. I went with this approach:
var myInt:Int = 10
var myString:String = toString(myInt)
Multiple ways to do this :
var str1:String="\(23)"
var str2:String=String(format:"%d",234)
let intAsString = 45.description // "45"
let stringAsInt = Int("45") // 45
Swift 2:
var num1 = 4
var numString = "56"
var sum2 = String(num1) + numString
var sum3 = Int(numString)
Swift String performance
A little bit about performance
UI Testing Bundle on iPhone 7(real device) with iOS 14
let i = 0
lt result1 = String(i) //0.56s 5890kB
lt result2 = "\(i)" //0.624s 5900kB
lt result3 = i.description //0.758s 5890kB
import XCTest
class ConvertIntToStringTests: XCTestCase {
let count = 1_000_000
func measureFunction(_ block: () -> Void) {
let metrics: [XCTMetric] = [
XCTClockMetric(),
XCTMemoryMetric()
]
let measureOptions = XCTMeasureOptions.default
measureOptions.iterationCount = 5
measure(metrics: metrics, options: measureOptions) {
block()
}
}
func testIntToStringConstructor() {
var result = ""
measureFunction {
for i in 0...count {
result += String(i)
}
}
}
func testIntToStringInterpolation() {
var result = ""
measureFunction {
for i in 0...count {
result += "\(i)"
}
}
}
func testIntToStringDescription() {
var result = ""
measureFunction {
for i in 0...count {
result += i.description
}
}
}
}
iam using this simple approach
String to Int:
var a = Int()
var string1 = String("1")
a = string1.toInt()
and from Int to String:
var a = Int()
a = 1
var string1 = String()
string1= "\(a)"
Convert Unicode Int to String
For those who want to convert an Int to a Unicode string, you can do the following:
let myInteger: Int = 97
// convert Int to a valid UnicodeScalar
guard let myUnicodeScalar = UnicodeScalar(myInteger) else {
return ""
}
// convert UnicodeScalar to String
let myString = String(myUnicodeScalar)
// results
print(myString) // a
Or alternatively:
let myInteger: Int = 97
if let myUnicodeScalar = UnicodeScalar(myInteger) {
let myString = String(myUnicodeScalar)
}
I prefer using String Interpolation
let x = 45
let string = "\(x)"
Each object has some string representation. This makes things simpler. For example if you need to create some String with multiple values. You can also do any math in it or use some conditions
let text = "\(count) \(count > 1 ? "items" : "item") in the cart. Sum: $\(sum + shippingPrice)"
exampleLabel.text = String(yourInt)
To convert String into Int
var numberA = Int("10")
Print(numberA) // It will print 10
To covert Int into String
var numberA = 10
1st way)
print("numberA is \(numberA)") // It will print 10
2nd way)
var strSomeNumber = String(numberA)
or
var strSomeNumber = "\(numberA)"
let a =123456888
var str = String(a)
OR
var str = a as! String
In swift 3.0, you may change integer to string as given below
let a:String = String(stringInterpolationSegment: 15)
Another way is
let number: Int = 15
let _numberInStringFormate: String = String(number)
//or any integer number in place of 15
If you like swift extension, you can add following code
extension Int
{
var string:String {
get {
return String(self)
}
}
}
then, you can get string by the method you just added
var x = 1234
var s = x.string
let Str = "12"
let num: Int = 0
num = Int (str)

Finding index of character in Swift String

It's time to admit defeat...
In Objective-C, I could use something like:
NSString* str = #"abcdefghi";
[str rangeOfString:#"c"].location; // 2
In Swift, I see something similar:
var str = "abcdefghi"
str.rangeOfString("c").startIndex
...but that just gives me a String.Index, which I can use to subscript back into the original string, but not extract a location from.
FWIW, that String.Index has a private ivar called _position that has the correct value in it. I just don't see how it's exposed.
I know I could easily add this to String myself. I'm more curious about what I'm missing in this new API.
You are not the only one who couldn't find the solution.
String doesn't implement RandomAccessIndexType. Probably because they enable characters with different byte lengths. That's why we have to use string.characters.count (count or countElements in Swift 1.x) to get the number of characters. That also applies to positions. The _position is probably an index into the raw array of bytes and they don't want to expose that. The String.Index is meant to protect us from accessing bytes in the middle of characters.
That means that any index you get must be created from String.startIndex or String.endIndex (String.Index implements BidirectionalIndexType). Any other indices can be created using successor or predecessor methods.
Now to help us with indices, there is a set of methods (functions in Swift 1.x):
Swift 4.x
let text = "abc"
let index2 = text.index(text.startIndex, offsetBy: 2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let characterIndex2 = text.index(text.startIndex, offsetBy: 2)
let lastChar2 = text[characterIndex2] //will do the same as above
let range: Range<String.Index> = text.range(of: "b")!
let index: Int = text.distance(from: text.startIndex, to: range.lowerBound)
Swift 3.0
let text = "abc"
let index2 = text.index(text.startIndex, offsetBy: 2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let characterIndex2 = text.characters.index(text.characters.startIndex, offsetBy: 2)
let lastChar2 = text.characters[characterIndex2] //will do the same as above
let range: Range<String.Index> = text.range(of: "b")!
let index: Int = text.distance(from: text.startIndex, to: range.lowerBound)
Swift 2.x
let text = "abc"
let index2 = text.startIndex.advancedBy(2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let lastChar2 = text.characters[index2] //will do the same as above
let range: Range<String.Index> = text.rangeOfString("b")!
let index: Int = text.startIndex.distanceTo(range.startIndex) //will call successor/predecessor several times until the indices match
Swift 1.x
let text = "abc"
let index2 = advance(text.startIndex, 2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let range = text.rangeOfString("b")
let index: Int = distance(text.startIndex, range.startIndex) //will call succ/pred several times
Working with String.Index is cumbersome but using a wrapper to index by integers (see https://stackoverflow.com/a/25152652/669586) is dangerous because it hides the inefficiency of real indexing.
Note that Swift indexing implementation has the problem that indices/ranges created for one string cannot be reliably used for a different string, for example:
Swift 2.x
let text: String = "abc"
let text2: String = "πŸŽΎπŸ‡πŸˆ"
let range = text.rangeOfString("b")!
//can randomly return a bad substring or throw an exception
let substring: String = text2[range]
//the correct solution
let intIndex: Int = text.startIndex.distanceTo(range.startIndex)
let startIndex2 = text2.startIndex.advancedBy(intIndex)
let range2 = startIndex2...startIndex2
let substring: String = text2[range2]
Swift 1.x
let text: String = "abc"
let text2: String = "πŸŽΎπŸ‡πŸˆ"
let range = text.rangeOfString("b")
//can randomly return nil or a bad substring
let substring: String = text2[range]
//the correct solution
let intIndex: Int = distance(text.startIndex, range.startIndex)
let startIndex2 = advance(text2.startIndex, intIndex)
let range2 = startIndex2...startIndex2
let substring: String = text2[range2]
Swift 3.0 makes this a bit more verbose:
let string = "Hello.World"
let needle: Character = "."
if let idx = string.characters.index(of: needle) {
let pos = string.characters.distance(from: string.startIndex, to: idx)
print("Found \(needle) at position \(pos)")
}
else {
print("Not found")
}
Extension:
extension String {
public func index(of char: Character) -> Int? {
if let idx = characters.index(of: char) {
return characters.distance(from: startIndex, to: idx)
}
return nil
}
}
In Swift 2.0 this has become easier:
let string = "Hello.World"
let needle: Character = "."
if let idx = string.characters.indexOf(needle) {
let pos = string.startIndex.distanceTo(idx)
print("Found \(needle) at position \(pos)")
}
else {
print("Not found")
}
Extension:
extension String {
public func indexOfCharacter(char: Character) -> Int? {
if let idx = self.characters.indexOf(char) {
return self.startIndex.distanceTo(idx)
}
return nil
}
}
Swift 1.x implementation:
For a pure Swift solution one can use:
let string = "Hello.World"
let needle: Character = "."
if let idx = find(string, needle) {
let pos = distance(string.startIndex, idx)
println("Found \(needle) at position \(pos)")
}
else {
println("Not found")
}
As an extension to String:
extension String {
public func indexOfCharacter(char: Character) -> Int? {
if let idx = find(self, char) {
return distance(self.startIndex, idx)
}
return nil
}
}
Swift 5.0
public extension String {
func indexInt(of char: Character) -> Int? {
return firstIndex(of: char)?.utf16Offset(in: self)
}
}
Swift 4.0
public extension String {
func indexInt(of char: Character) -> Int? {
return index(of: char)?.encodedOffset
}
}
extension String {
// MARK: - sub String
func substringToIndex(index:Int) -> String {
return self.substringToIndex(advance(self.startIndex, index))
}
func substringFromIndex(index:Int) -> String {
return self.substringFromIndex(advance(self.startIndex, index))
}
func substringWithRange(range:Range<Int>) -> String {
let start = advance(self.startIndex, range.startIndex)
let end = advance(self.startIndex, range.endIndex)
return self.substringWithRange(start..<end)
}
subscript(index:Int) -> Character{
return self[advance(self.startIndex, index)]
}
subscript(range:Range<Int>) -> String {
let start = advance(self.startIndex, range.startIndex)
let end = advance(self.startIndex, range.endIndex)
return self[start..<end]
}
// MARK: - replace
func replaceCharactersInRange(range:Range<Int>, withString: String!) -> String {
var result:NSMutableString = NSMutableString(string: self)
result.replaceCharactersInRange(NSRange(range), withString: withString)
return result
}
}
I have found this solution for swift2:
var str = "abcdefghi"
let indexForCharacterInString = str.characters.indexOf("c") //returns 2
I'm not sure how to extract the position from String.Index, but if you're willing to fall back on some Objective-C frameworks, you can bridge to objective-c and do it the same way you used to.
"abcdefghi".bridgeToObjectiveC().rangeOfString("c").location
It seems like some NSString methods haven't yet been (or maybe won't be) ported to String. Contains also comes to mind.
Here is a clean String extention that answers the question:
Swift 3:
extension String {
var length:Int {
return self.characters.count
}
func indexOf(target: String) -> Int? {
let range = (self as NSString).range(of: target)
guard range.toRange() != nil else {
return nil
}
return range.location
}
func lastIndexOf(target: String) -> Int? {
let range = (self as NSString).range(of: target, options: NSString.CompareOptions.backwards)
guard range.toRange() != nil else {
return nil
}
return self.length - range.location - 1
}
func contains(s: String) -> Bool {
return (self.range(of: s) != nil) ? true : false
}
}
Swift 2.2:
extension String {
var length:Int {
return self.characters.count
}
func indexOf(target: String) -> Int? {
let range = (self as NSString).rangeOfString(target)
guard range.toRange() != nil else {
return nil
}
return range.location
}
func lastIndexOf(target: String) -> Int? {
let range = (self as NSString).rangeOfString(target, options: NSStringCompareOptions.BackwardsSearch)
guard range.toRange() != nil else {
return nil
}
return self.length - range.location - 1
}
func contains(s: String) -> Bool {
return (self.rangeOfString(s) != nil) ? true : false
}
}
You can also find indexes of a character in a single string like this,
extension String {
func indexes(of character: String) -> [Int] {
precondition(character.count == 1, "Must be single character")
return self.enumerated().reduce([]) { partial, element in
if String(element.element) == character {
return partial + [element.offset]
}
return partial
}
}
}
Which gives the result in [String.Distance] ie. [Int], like
"apple".indexes(of: "p") // [1, 2]
"element".indexes(of: "e") // [0, 2, 4]
"swift".indexes(of: "j") // []
Swift 5
Find index of substring
let str = "abcdecd"
if let range: Range<String.Index> = str.range(of: "cd") {
let index: Int = str.distance(from: str.startIndex, to: range.lowerBound)
print("index: ", index) //index: 2
}
else {
print("substring not found")
}
Find index of Character
let str = "abcdecd"
if let firstIndex = str.firstIndex(of: "c") {
let index: Int = str.distance(from: str.startIndex, to: firstIndex)
print("index: ", index) //index: 2
}
else {
print("symbol not found")
}
If you want to use familiar NSString, you can declare it explicitly:
var someString: NSString = "abcdefghi"
var someRange: NSRange = someString.rangeOfString("c")
I'm not sure yet how to do this in Swift.
If you want to know the position of a character in a string as an int value use this:
let loc = newString.range(of: ".").location
This worked for me,
var loc = "abcdefghi".rangeOfString("c").location
NSLog("%d", loc);
this worked too,
var myRange: NSRange = "abcdefghi".rangeOfString("c")
var loc = myRange.location
NSLog("%d", loc);
I know this is old and an answer has been accepted, but you can find the index of the string in a couple lines of code using:
var str : String = "abcdefghi"
let characterToFind: Character = "c"
let characterIndex = find(str, characterToFind) //returns 2
Some other great information about Swift strings here Strings in Swift
Variable type String in Swift contains different functions compared to NSString in Objective-C . And as Sulthan mentioned,
Swift String doesn't implement RandomAccessIndex
What you can do is downcast your variable of type String to NSString (this is valid in Swift). This will give you access to the functions in NSString.
var str = "abcdefghi" as NSString
str.rangeOfString("c").locationx // returns 2
If you think about it, you actually don't really need the exact Int version of the location. The Range or even the String.Index is enough to get the substring out again if needed:
let myString = "hello"
let rangeOfE = myString.rangeOfString("e")
if let rangeOfE = rangeOfE {
myString.substringWithRange(rangeOfE) // e
myString[rangeOfE] // e
// if you do want to create your own range
// you can keep the index as a String.Index type
let index = rangeOfE.startIndex
myString.substringWithRange(Range<String.Index>(start: index, end: advance(index, 1))) // e
// if you really really need the
// Int version of the index:
let numericIndex = distance(index, advance(index, 1)) // 1 (type Int)
}
The Simplest Way is:
In Swift 3:
var textViewString:String = "HelloWorld2016"
guard let index = textViewString.characters.index(of: "W") else { return }
let mentionPosition = textViewString.distance(from: index, to: textViewString.endIndex)
print(mentionPosition)
String is a bridge type for NSString, so add
import Cocoa
to your swift file and use all the "old" methods.
In terms of thinking this might be called an INVERSION. You discover the world is round instead of flat. "You don't really need to know the INDEX of the character to do things with it." And as a C programmer I found that hard to take too!
Your line "let index = letters.characters.indexOf("c")!" is enough by itself.
For example to remove the c you could use...(playground paste in)
var letters = "abcdefg"
//let index = letters.rangeOfString("c")!.startIndex //is the same as
let index = letters.characters.indexOf("c")!
range = letters.characters.indexOf("c")!...letters.characters.indexOf("c")!
letters.removeRange(range)
letters
However, if you want an index you need to return an actual INDEX not an Int as an Int value would require additional steps for any practical use. These extensions return an index, a count of a specific character, and a range which this playground plug-in-able code will demonstrate.
extension String
{
public func firstIndexOfCharacter(aCharacter: Character) -> String.CharacterView.Index? {
for index in self.characters.indices {
if self[index] == aCharacter {
return index
}
}
return nil
}
public func returnCountOfThisCharacterInString(aCharacter: Character) -> Int? {
var count = 0
for letters in self.characters{
if aCharacter == letters{
count++
}
}
return count
}
public func rangeToCharacterFromStart(aCharacter: Character) -> Range<Index>? {
for index in self.characters.indices {
if self[index] == aCharacter {
let range = self.startIndex...index
return range
}
}
return nil
}
}
var MyLittleString = "MyVery:important String"
var theIndex = MyLittleString.firstIndexOfCharacter(":")
var countOfColons = MyLittleString.returnCountOfThisCharacterInString(":")
var theCharacterAtIndex:Character = MyLittleString[theIndex!]
var theRange = MyLittleString.rangeToCharacterFromStart(":")
MyLittleString.removeRange(theRange!)
Swift 4 Complete Solution:
OffsetIndexableCollection (String using Int Index)
https://github.com/frogcjn/OffsetIndexableCollection-String-Int-Indexable-
let a = "01234"
print(a[0]) // 0
print(a[0...4]) // 01234
print(a[...]) // 01234
print(a[..<2]) // 01
print(a[...2]) // 012
print(a[2...]) // 234
print(a[2...3]) // 23
print(a[2...2]) // 2
if let number = a.index(of: "1") {
print(number) // 1
print(a[number...]) // 1234
}
if let number = a.index(where: { $0 > "1" }) {
print(number) // 2
}
extension String {
//Fucntion to get the index of a particular string
func index(of target: String) -> Int? {
if let range = self.range(of: target) {
return characters.distance(from: startIndex, to: range.lowerBound)
} else {
return nil
}
}
//Fucntion to get the last index of occurence of a given string
func lastIndex(of target: String) -> Int? {
if let range = self.range(of: target, options: .backwards) {
return characters.distance(from: startIndex, to: range.lowerBound)
} else {
return nil
}
}
}
You can find the index number of a character in a string with this:
var str = "abcdefghi"
if let index = str.firstIndex(of: "c") {
let distance = str.distance(from: str.startIndex, to: index)
// distance is 2
}
If you are looking for easy way to get index of Character or String checkout this library http://www.dollarswift.org/#indexof-char-character-int
You can get the indexOf from a string using another string as well or regex pattern
To get index of a substring in a string with Swift 2:
let text = "abc"
if let range = text.rangeOfString("b") {
var index: Int = text.startIndex.distanceTo(range.startIndex)
...
}
In swift 2.0
var stringMe="Something In this.World"
var needle="."
if let idx = stringMe.characters.indexOf(needle) {
let pos=stringMe.substringFromIndex(idx)
print("Found \(needle) at position \(pos)")
}
else {
print("Not found")
}
let mystring:String = "indeep";
let findCharacter:Character = "d";
if (mystring.characters.contains(findCharacter))
{
let position = mystring.characters.indexOf(findCharacter);
NSLog("Position of c is \(mystring.startIndex.distanceTo(position!))")
}
else
{
NSLog("Position of c is not found");
}
I play with following
extension String {
func allCharactes() -> [Character] {
var result: [Character] = []
for c in self.characters {
result.append(c)
}
return
}
}
until I understand the provided one's now it's just Character array
and with
let c = Array(str.characters)
If you only need the index of a character the most simple, quick solution (as already pointed out by Pascal) is:
let index = string.characters.index(of: ".")
let intIndex = string.distance(from: string.startIndex, to: index)
On the subject of turning a String.Index into an Int, this extension works for me:
public extension Int {
/// Creates an `Int` from a given index in a given string
///
/// - Parameters:
/// - index: The index to convert to an `Int`
/// - string: The string from which `index` came
init(_ index: String.Index, in string: String) {
self.init(string.distance(from: string.startIndex, to: index))
}
}
Example usage relevant to this question:
var testString = "abcdefg"
Int(testString.range(of: "c")!.lowerBound, in: testString) // 2
testString = "πŸ‡¨πŸ‡¦πŸ‡ΊπŸ‡ΈπŸ‡©πŸ‡ͺπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦\u{1112}\u{1161}\u{11AB}"
Int(testString.range(of: "πŸ‡¨πŸ‡¦πŸ‡ΊπŸ‡ΈπŸ‡©πŸ‡ͺ")!.lowerBound, in: testString) // 0
Int(testString.range(of: "πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦")!.lowerBound, in: testString) // 1
Int(testString.range(of: "ᄒᅑᆫ")!.lowerBound, in: testString) // 5
Important:
As you can tell, it groups extended grapheme clusters and joined characters differently than String.Index. Of course, this is why we have String.Index. You should keep in mind that this method considers clusters to be singular characters, which is closer to correct. If your goal is to split a string by Unicode codepoint, this is not the solution for you.
In Swift 2.0, the following function returns a substring before a given character.
func substring(before sub: String) -> String {
if let range = self.rangeOfString(sub),
let index: Int = self.startIndex.distanceTo(range.startIndex) {
return sub_range(0, index)
}
return ""
}
As my perspective, The better way with knowing the logic itself is below
let testStr: String = "I love my family if you Love us to tell us I'm with you"
var newStr = ""
let char:Character = "i"
for value in testStr {
if value == char {
newStr = newStr + String(value)
}
}
print(newStr.count)

Resources