Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of type 'String' has no member 'range' in Swift

Tags:

swift

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)){
                                    ^~~~ ~~~~~
like image 893
Laurence Wingo Avatar asked Mar 10 '23 05:03

Laurence Wingo


1 Answers

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          
}
like image 109
Rohan Sanap Avatar answered Mar 12 '23 17:03

Rohan Sanap