在单独的.swift文件中使用扩展 [英] Using extensions in separate .swift file

查看:98
本文介绍了在单独的.swift文件中使用扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找在单独的文件或替代解决方案中使用Swift扩展的方法。只有在将扩展名写入正在使用的文件中时,才能创建扩展。

Looking for a way to use Swift extensions in a separate file or an alternative solution. Creating an extension only works as long as the extension is written in the same file it is being used.

以下是适用的ViewController.swift示例。

Here is an example of the ViewController.swift that works.

import UIKit
var TestHelper: String = "Start Value"
extension UIView {
var testValue:String{
set{
    TestHelper = newValue
}
get{
    return  TestHelper
}
}
}

class ViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    self.view.testValue = "Some Value"
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
}

将扩展名从此文件中取出并放入新文件结果在崩溃中发出此错误:

Taking the extension out of this file and placing in a new file results in a crash giving this error:

Program ended with exit code: 9

这个错误说我认为它不存在。在扩展所需的每个单独文件中创建扩展名显然会产生无效重新声明的问题。

This error is saying it doesn't exist I think. Creating the extension in each separate file that the extension is need obviously creates issues with invalid redeclaration.

提前致谢!

推荐答案

如果您将扩展程序移至另一个文件,你也必须移动TestHelper。或者更简单:将TestHelper放入扩展名

If you move the extension to another file then you have to move TestHelper, too. Or simplier: put TestHelper into the extension

这篇关于在单独的.swift文件中使用扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆