修改 Swift 本身

Modify Swift itself

是否可以修改Swift本身?

我一直使用一些函数,而不是通过复制和粘贴将这些函数添加到每个 .swift 文件或我的代码片段库中的用户集合,我希望它们是顶级的函数。

为了尝试实现这一点,我创建了一个包含这些函数的 LanguageModifications.swift 文件。这最初有效,但最终以呈现视图和过于复杂的问题告终。

LanguageModifications.swift

import Foundation
import UIKit

class LanguageModifications: UIViewController {
    // Timed delays
    func delay(delay:Double, closure:()->()) {
        dispatch_after(
            dispatch_time(
                DISPATCH_TIME_NOW,
                Int64(delay * Double(NSEC_PER_SEC))
            ),
            dispatch_get_main_queue(), closure)
    }

    // Alert
    func alertWithTitleAndMessage(title: String, message: String) {
        var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }
}

有没有办法将这些函数添加到 Swift 语言本身,这样我就可以在每个文件中不假思索地访问它们?谢谢!

您是否考虑过使用 Swift 的 Extensions

Extensions add new functionality to an existing class, structure, or enumeration type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions do not have names.)

只需将您的函数(如 delay 声明为文件中的函数,而不是在任何 class 或结构中。这不是 Java,函数不需要陪伴 :-)

Swift 标准库充满了 classes 中没有的函数,例如 printlnmapsort(那些后两者类似于 Array 上的方法,但适用于任何类型的集合。

这并不是真正的“修改”Swift。这就是 Swift 的工作原理——定义函数并使用它们。根本没有必须使用 classes 的规则。

您应该可以使用 Swift 的 Extensions 功能。

正如 Apple 的开发者网站所描述的那样,扩展允许您使用协议扩展现有类型。例如,扩展 Double 数据类型以包含单位转换函数。

您应该能够在 UIViewController 的扩展中定义您的 alertWithTitleAndMessage 函数:

extension UIViewController: LanguageModifications {
    // Alert
    func alertWithTitleAndMessage(title: String, message: String) {
        var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }
}

以上将扩展 UIViewController 并添加 alertWithTitleAndMessage.

的定义

对于delay,你真的不需要在扩展中定义它。正如 Airspeed Velocity 所指出的,它可能是另一个 *.swift 文件中的松散函数。它不依赖 UIViewController 实例,因此没有理由将它添加到每个实例。