I believe I've run into a Swift versioning issue but I'm not too sure. The code works in my Xcode platform but not in an online swift compiler. Has anyone else run into this issue or know what I can use to replace the following lines where I check for a character:
if i == 0 || !((line.range(of: ":") != nil))
Here is my code:
import Foundation
func hackTheString(line: String){
var maxOpen: Int = 0
var minOpen: Int = 0
minOpen = 0
maxOpen = 0
let i = 0
while i < line.characters.count {
for character in line.characters {
if character == "(" {
maxOpen += 1
if i == 0 || !((line.range(of: ":") != nil)) {
minOpen += 1
}
}
else if character == ")"{
minOpen = max(0,minOpen-1)
if i == 0 || !((line.range(of: ":") != nil)){
maxOpen -= 1;
}
if maxOpen < 0{
break
}
}
}
if maxOpen >= 0 && minOpen == 0{
print("YES")
}else{
print("NO")
}
}
}
while let line = readLine() {
print(hackTheString(line))
}
The error given from the online compiler is:
source.swift:17:37: error: value of type 'String' has no member 'range'
if i == 0 || !((line.range(of: ":") != nil)) {
^~~~ ~~~~~
source.swift:24:37: error: value of type 'String' has no member 'range'
if i == 0 || !((line.range(of: ":") != nil)){
^~~~ ~~~~~
I tried using range(of:)
function on IBM's online swift compiler and I made sure to write import Foundation
and it totally worked. Then I tried to see what version of swift is that online compiler using with following code:
#if swift(>=3.0)
print("Hello, Swift 3!")
#elseif swift(>=2.2)
print("Hello, Swift 2.2!")
#elseif swift(>=2.1)
print("Hello, Swift 2.1!")
#endif
That way I got to know that the online compiler I tried was using Swift 3 and hence the function worked perfect. Try checking what version your online compiler is using and use the related function specific to that version.
Other thing that you can do for now is use the characters array of your string and find the Index
of your character. So your code might look like this:
if i == 0 || !((line.characters.index(of: ":") != nil)) {
minOpen += 1
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With