我相信我遇到了Swift版本问题,但我不太确定.代码可以在我的Xcode平台上运行,但不能在在线swift编译器中运行.有没有其他人遇到这个问题或知道我可以用什么来替换我检查字符的以下行:
if i == 0 || !((line.range(of: ":") != nil))
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
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))
}
Run Code Online (Sandbox Code Playgroud)
在线编译器给出的错误是:
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)){
^~~~ ~~~~~
Run Code Online (Sandbox Code Playgroud)
我尝试range(of:)在IBM的在线swift编译器上使用函数,我确保编写import Foundation它完全有效.然后我试着看看使用以下代码的在线编译器是什么版本的swift:
#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
Run Code Online (Sandbox Code Playgroud)
这样我就知道我尝试的在线编译器使用的是Swift 3,因此功能完美无缺.尝试检查您的在线编译器使用的版本,并使用特定于该版本的相关功能.
您现在可以做的其他事情是使用字符串的characters数组并找到Index您的角色.所以你的代码可能如下所示:
if i == 0 || !((line.characters.index(of: ":") != nil)) {
minOpen += 1
}
Run Code Online (Sandbox Code Playgroud)