如何在swift中比较String和任何类型是否相等?

时间:2017-03-25 08:10:40

标签: swift string if-statement

例如,
let a: String = "sat" let b: Any = "sat"

if a == b

我之前尝试过。但是它显示了不匹配的类型字符串和任何 请帮助我解决这个问题。我是swift的新手。

3 个答案:

答案 0 :(得分:2)

尝试以下

if(a == "\(b)") // b automatically converted into 'Any' to 'String'
{
   ...
   ...
   ...
}

答案 1 :(得分:2)

不同的是var a是String,var b是Any(anyObject),所以你可以保持它们的平等。因此,在比较或比较之前,解决方法是将var b更改为String类型

If a == (b as! String){    }

If a == "/(b)"{    }

答案 2 :(得分:1)

如果您遇到该错误,请先检查它是什么类型的数据。

(defproject app "0.1.0-SNAPSHOT"
  :main app.core ; 2.
  :description "First Application"
  :url ""
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.8.0"]])

它显示了我的字符串

enter image description here

现在我们可以通过以下方式检查

如果我们用字符串键入cast b,问题已经消失了。

let b: Any = "sat"
print(type(of: b))