Usage of String.range in Swift 3.0 - ios

let us = "http://example.com"
let range = us.rangeOfString("(?<=://)[^.]+(?=.com)", options:.RegularExpressionSearch)
if range != nil {
let found = us.substringWithRange(range!)
print("found: \(found)") // found: example
}
This code extracts substring between backslashes and dot com in Swift 2. I searched Internet and I found that rangeOfString changed to range().
But still I could not make the code work in Swift 3.0. Could you help me ?
edit : I'm using swift 3 07-25 build.

In swift 3.0 rangeOfString syntax changed like this.
let us = "http://example.com"
let range = us.range(of:"(?<=://)[^.]+(?=.com)", options:.regularExpression)
if range != nil {
let found = us.substring(with: range!)
print("found: \(found)") // found: example
}

In latest swift 3.0 using Xcode 8 Beta 6 (latest updates to SDK):
let us = "http://example.com"
let range = us.range(of: "(?<=://)[^.]+(?=.com)", options: .regularExpression)
if range != nil {
let found = us.substring(with: range!)
print("found: \(found)") // found: example
}

Related

Processing payments code written in Swift 2, not sure about Swift 3 equivalent

So I have some code to process payments that I'm copying from a website:
if self.expireDateTextField.text.isEmpty == false {
let expirationDate = self.expireDateTextField.text.componentsSeparatedByString("/")
let expMonth = UInt(expirationDate[0].toInt()!)
let expYear = UInt(expirationDate[1].toInt()!)
I know toInt() was removed but what be the equivalent of the code above?
The Swift 3 equivalent of toInt() is simply Int():
let expMonth = UInt(Int(expirationDate[0])!)!
let expYear = UInt(Int(expirationDate[1]!))!
In your case, I would make two refinements in the code. Firstly, you are converting two times, which is not neccesary, you may use UInt() only.
Secondly, you may consider not to implicitly unwrap, as it could easily cause a crash.
guard let expMonth = UInt(expirationDate[0]),
let expYear = UInt(expirationDate[1]) else {
print("Error in expiration casting")
return
}

Value of type 'String' has no member 'substringToIndex' not resolved

I am trying to grab currentLanguage of a device using the below function. But there has been an issue with substring and I don't seem to understand as previous answers have such simple solution of importing Foundation to the file, which didn't work for me.
class func currentLanguage() -> String
{
let str = "en-US"
if let indexOfDash = str.characters.index(of: "-")
{
let langCode = str.substringToIndex(indexOfDash)
return langCode
}
}
In addition, What can be the best approach to get current language?
You need to use
let langCode = str.substring(to: indexOfDash)
And you can get current language like that:
let pre = NSLocale.preferredLanguages[0]

Need to update Swift code to the newest version

Prior to the new Swift version I was using the following code in my app.
Now it launches an exception.
for (i, in 0 ..< len){
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}
XCode says:
Expected pattern
Expected "," separator
Expected "in" after for-each pattern
Expected SequenceType expression for for-each loop
Changing the code with the proposed solutions doesn't change the exceptions thrown.
Any help is welcome to update the code to the current Swift version.
For for syntax you are using have been deprecated, and should be changed to
for _ in 0..<len
// rest of your code
the question already has correct answer still i have converted it so posting here may be some get help from it
let len = 5
let letters:NSString = "str"
for i in 0 ..< len {
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
let randomString:NSMutableString = ""
randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}
As some of the variable are not shown in the code i have made them based on the parameters

iOS Swift manipulate/parse string

I'm not sure how to do this in iOS Swift
let test = "fnfsjflsjlkdkfj?v=904kg4"
// search test for ?v= and store everything after ?v= into a new string
let newString = "904kg4"
I want everything after ?v= into a new string, is this possible? if so, how can I accomplish this
Use rangeOfString to find the range of ?v= and then use substringFromIndex to get the rest of the string:
let test = "fnfsjflsjlkdkfj?v=904kg4"
if let range = test.rangeOfString("?v=") {
let newString = test.substringFromIndex(range.endIndex)
}

Swift 1.2 lowercaseString crashes with enumerateSubstringInRange

Just converted my code to Swift 1.2. I'm getting a BAD_EXEC_ACCESS with the below code:
var wordsBeingTyped = NSString()
var lastWord = String()
wordsBeingTyped = proxy.documentContextBeforeInput // Gets the string being typed
let range = NSMakeRange(0, (wordsBeingTyped).length)
wordsBeingTyped.enumerateSubstringsInRange(range, options: NSStringEnumerationOptions.ByWords) { (substring, substringRange, enclosingRange, stop) -> () in
lastWord = substring // The last word in the string wordsBeingTyped
}
let lastWordLowercase = lastWord.lowercaseString
The crash is happening on the last line. For testing purposes I changed that line to:
let lastWordLowercase = wordsBeingTyped.lowercaseString
And it works just fine. The strange thing is it only crashes when I'm typing the first word in a string. After a space character there is no crashing.
Update: The work around I came up with is to make a new let to convert wordsBeingTyped to lowercase before using enumerateSubstringsInRange. So:
let lowercaseWordsBeingTyped = wordsBeingTyped.lowercaseString
// ..enumerate string to get last word typed
let lastWordLowercase = lastWord
Hope that helps someone.
This was a bug in Xcode 6.3 beta 1. It's fixed in Xcode 6.3 beta 2.

Resources