嗨,在 Swift 中编写静态扩展是否有任何变化,就像在 C# 中一样?我的意思是在 C# 中我可以写同样的东西,如下所示:
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
并这样调用它:
var s = ""; var x = s.WordCount();
我知道我可以在 swift 中做同样的事情,但它只适用于类类型。在静态类型上我必须写一些类似的东西:
var str:String?
let s = String.IsNilOrEmpty(str)
对于此扩展:
extension String {
static func isNilOrEmpty(str: String?) -> Bool{
if str == nil {
return true
}
if str!.isEmpty{
return true
}
return false
}
}
是否有更改可以这样称呼:
let s = str.IsNilOrEmpty()
感谢您的帮助或采取正确的方式。
最佳答案
您可以定义具有相同名称的函数,一个是静态的,一个是非静态的。
extension String {
static func myfunc() -> String {
return "static"
}
func myfunc() -> String {
return "func"
}
}
let s3 = ""
print(s3.myfunc()) // output = "func"
print(String.myfunc()) // output = "static"
在这种情况下,如果 'someOptionalString' 为 nil,则不会调用该函数。
let some = someOptionalString.IsNilOrEmpty()
关于c# - 像 c# 一样的 swift 静态扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36115513/