ios - 如何从扩展访问变量并在 Swift 的 View Controller 中使用它

标签 ios swift variables uiviewcontroller scope

该值已正确打印到标签,但我想显示 bubbleSort() 中的每次迭代。因此,我在每次迭代时都给出了一些打印命令。但是,它仅打印在控制台上。我想将每次迭代打印到 Label2 上。

我最终在从 View Controller 中的扩展访问变量时遇到了麻烦。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var userArr: UITextField!
    @IBOutlet weak var Label: UILabel!
    @IBOutlet weak var Label2: UILabel!

    @IBAction func sortBtn(_ sender: Any) {
        let strings = userArr.text

        let digs = strings?.digits

        var arrayIntegers = strings?.components(separatedBy: " ").flatMap { Int($0) }

        let t = arrayIntegers!.bubbleSort()

        Label.text = "\(t)"

        Label2.text = "" //This is where each iteration should be. 
       // "\(bubbleSort.a)" + "\(b)" + "\(c)" tried something similar to that 
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
}

extension Array where Element: Comparable {
    func bubbleSort (by areInIncreasingOrder: ((Element, Element) -> Bool) = (<)) ->[Element] {
        var data = self
        let a = print(data) //prints first iteration

        for i in 0..<(data.count-1){
            for j in 0..<(data.count-i-1) where areInIncreasingOrder(data[j+1], data[j]){
                let b = print(data) // print iteration n+1 to n-1
                data.swapAt(j, j+1)

            }
        }

        var c = print(data) // print last iteration

        return data
    }
}

最佳答案

您尝试了joined方法?

像这样:

Label2.text = bubbleSort.joined(separator: "\n")

关于ios - 如何从扩展访问变量并在 Swift 的 View Controller 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57384936/

相关文章:

ios - CollectionView sizeForItemAtIndexPath 从未调用过

ios - IQKeyboardManager 错误 : Value of type 'UIView' has no member 'keyboardToolbar'

ios - 如何在 Swift 中对两种类型进行协议(protocol)扩展约束

javascript - 为什么这些值彼此不相等?

python - 如何在Python中列出自己定义的所有变量,不包括导入的变量?

android - 设置全局 gradle build dir 相对路径

iOS检测设备密码锁是否开启

ios - Crossfade 多个 UIViews 没有背景通过 alpha 偷看?

macos - 适用于 iOS 和 Mac 项目的构建工具

swift - 如何拥有多个同名节点,每个节点分别与环境交互