removeRange() function gives empty string in Swift 2 - swift2

The removeRange: is giving me an empty string in Swift 2 and I don't understand why.
The example in the apple documentation is:
var welcome = "hello!"
let range = welcome.endIndex.advancedBy(-6)..<welcome.endIndex
welcome.removeRange(range)
//I get "" as result rather than "hello" where the exclamation mark is removed
What could be the problem?

You start at the endIndex and then you go back by 6. You are now at the beginning of the word. Then you make a range to the end index and you remove the content of this range: of course there's nothing left. :)
For example, it could be this instead:
var welcome = "hello!"
let range = welcome.endIndex.advancedBy(-1)..<welcome.endIndex
welcome.removeRange(range)
Or this:
var welcome = "hello!"
let range = welcome.startIndex.advancedBy(5)..<welcome.endIndex
welcome.removeRange(range)
There's many possible combinations.

the string in apple documentation is
at the time of remove range
var welcome = "hello there!"

The value of welcome.endIndex is 6 so advancedBy(-6) means it goes to 0. Then the range = 0..<6 that means the the range cover the whole string.
If you want "hello" then change only advancedBy(-1).
var welcome = "hello!"
let range = welcome.endIndex.advancedBy(-1)..<welcome.endIndex
welcome.removeRange(range)

Related

Python Reverse Loop

name = "Hello World and Good Morning"
letnum = ""
for let in name:
if let.isdigit() == False:
letnum += let
print(letnum)
I am trying to find a way to reverse this loop. I want it to start with the word fully spelled and then end with one letter left.
Here is one way to do it: it lets an integer go from the full string length down to 1, and displays each time that many characters of the original string:
name = "Hello World and Good Morning"
for length in range(len(name), 0, -1):
if not name[length - 1].isdigit():
print(name[:length])

How to avoid optional word from the app?

I removed optional from assistance editor by unwrapping but how to get rid of it in the app and get only the number in answer and not the optional word with it?
Since there are two optionals(text from textfield, String to Integer typecasting) you can use the multiple if let conditions here
if let catText = catAge.text ,let cat = Int(catText) {
let age = cat * 7
catAge.text = "your cat is \(age) years old"
}

Manipulating strings with Swift

I am trying to divide a String in Swift. I have the following string
Program - /path/to/file.doc
I want to get three informations out of this string
Program
/path/to/file.doc
file.doc
I began with the following solution
var str = "Program - /path/to/file.doc"
let indi = str.rangeOfString("-")?.startIndex
let subString = str.substringWithRange(Range<String.Index>(start: str.startIndex, end: indi!))
let subString2 = str.substringWithRange(Range<String.Index>(start: indi!, end: str.endIndex))
This gives me the results
"Program "and
"- /path/to/file.doc"
But how can I get file.doc after the last /?
How Can i increase/decrease and range index to avoid blank spaces?
Yes, sidyll's suggestion is correct, it's a very common practice to get components of Unix path by converting it to NSURL. You may want to write something like this:
var str = "Program - /path/to/file.doc"
if let indi = str.rangeOfString(" - ")?.startIndex {
let subString = str.substringWithRange(Range<String.Index>(start: str.startIndex, end: indi))
let subString2 = str.substringWithRange(Range<String.Index>(start: indi, end: str.endIndex))
let fileName = NSURL(string: subString2).lastPathComponent()
}
I strongly suggest you don't do force unwrap like this. Consider situation if this code will work with string without a particular pattern, for example empty string. Correct, runtime error.

Dictionary Optional? Confusion in swift

I know there are a lot of posts on this, but I can't seem to figure out what's going on. The dictionary prints fine. It has a list of words with the number of letters for that word as the value. I want to check if another string is in the list. I read a bunch on optionals, but apparently I'm missing something. I think it has to do with that of course.
let path = NSBundle.mainBundle().pathForResource("wordlist", ofType: "txt")
var content = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)?.componentsSeparatedByString("\n")
var myDict = [String : Int]()
let compareWord : String? = "TEST"
if let content = content {
for word in 100 ..< 105
{
myDict[content[word]] = countElements(content[word])
}
}
println("\(myDict)")
var num : Int? = 0
println("Num: \(myDict[compareWord!])")
if let num : Int = myDict[compareWord!] {
println("\(compareWord) is a word with \(num) letters")
}
else
{
println("Wasn't a word")
}
**** Updated with a bit more detail of the code.
Here is what I get when I print a section of the dictionary.
[ABBOTSHIPS
: 11, ABBREVIATED
: 12, ABBOTS
: 7, ABBOTSHIP
: 10, ABBREVIATE
: 11]
If I set the test word to one of them I always get nil when checking for it. It seems to work fine when I manually type things in under the playground.
Ensure that componentsSeparatedByString("\n") doesn't leave any other character, such as \r, at the beginning or end of each extracted strings.

Can't convert String into Integer (TypeError)

I am learning Ruby
I am trying to create a simple script that will convert a given number to roman numerals (old style roman numerals)
I am unable to understand why I get the "can't convert String into Integer (TypeError)"
def convert_to_roman number
romans_array = [[1000,'M'],[500,'D'],[100,'C'],[50,'L'],[10,'X'],[5,'V'][1,'I']]
converted_array = []
romans_array.each do |rom_num|
num = rom_num[0]
letter = rom_num[1]
if number > num
times = number / num
roman_letter = letter*times
converted_array.push(roman_letter)
number = number % num
end
end
converted_array.join()
end
number = ''
puts 'please write a number and I will convert it to old style Roman numerals :)'
puts 'p.s. to exit this program simply hit enter on an empty line, or type 0 and enter :)'
while number != 0
number = gets.chomp.to_i
puts convert_to_roman number
end
My code is at:
https://github.com/stefanonyn/ruby-excercises/blob/master/roman_numerals.rb
You will see that at the end of the file commented out there is an old revision of the code, which actually does work but has a lot of repetition.
I would appreciate if someone could clarify why I get the error described above.
Please don't write the code for me, I am trying to learn Ruby, I would appreciate just some support in moving to the next step.
Thank you very much!
You are missing a comma in your array
romans_array = [[1000,'M'],[500,'D'],[100,'C'],[50,'L'],[10,'X'],[5,'V'][1,'I']]
^ here
This error is definitely not all that helpful, but the reason that it is appearing is that to the interpreter it looks like you are attempting to access a range of indexes in the [5,'V'] array for the last element. However the index's that are being provided go from 1 to 'I' which of course makes no sense. If it had been written [5,'V'][1,1] the last element of the array would be ['V'], which might have been even more confusing to debug!

Resources