c# - 像 c# 一样的 swift 静态扩展

标签 c# swift

嗨,在 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/

相关文章:

c# - C# 的多个异常的 XML 文档

ios - 从 Firebase Swift 3.0 检索数据时出现问题

ios - Swift:自定义 UIView.transition 有问题吗?

ios - Swift 在每个部分中选择一个单元格

ios - SwipeCellKit 操作不会执行 segue

c# - 如何仅在 wpf 列表框的一行上更改前景色?

c# - 如何在 C# 中将文本框置于边框内居中

c# - 如何使用 HttpWebRequest 发布数据?

c# - 在表之间迁移数据的整洁方式?

ios - 如何在更改 View 的同时仍然让用户在 TextField 中进行编辑?