我在 swift 中有两个类,TestView()
和 compileResults()
。
我在 compileResults()
中有返回值的函数。我需要将该值返回给 TestView()
。
我已经设法从 TestView()
中在 compileResults()
中设置了一个值,但我似乎无法返回一个值。
我已经按照在其他地方使用委托(delegate)的相同方式设置了委托(delegate),但它似乎仍然没有产生结果。
测试 View :
import UIKit
import Foundation
class TestView: UIViewController, XMLParserDelegate {
weak var resStartDelegate: ResStartDelegate?
override func viewDidLoad() {
super.viewDidLoad()
resStartDelegate?.setConTypeResult(val: "WiFi")
print("ConType is: ", resStartDelegate?.getConTypeResult()) //outputs value nil
}
编译结果:
import Foundation
protocol ResStartDelegate: class {
func getConTypeResult() -> String
func setConTypeResult(val: String)
}
var testViewDelegate = TestView()
var theTestResults : [String: String] = [
"conType": ""
]
class complileResults : ResStartDelegate {
init() {
setDelegate()
}
func setDelegate() {
testViewDelegate.resStartDelegate = self
}
func resetResults() {
theTestResults["conType"] = ""
}
func setConTypeResult(val: String) {
theTestResults["conType"] = val
print("Just set contype to: ", theTestResults["conType"]) //prints correctly what has been passed from TestView
}
func getConTypeResult() -> String {
return theTestResults["conType"] ?? "Err"
}
}
编辑:这似乎如我所愿,有什么问题吗?
编译结果.swift
import Foundation
class complileResults {//: ResStartDelegate {
var theTestResults : [String: String] = [
"conType": "",
"date": "",
"time": "",
"jitter": "",
"loss": "",
"dspeed": "",
"uspeed": "",
"delay": ""
]
func setConTypeResult(val: String) {
theTestResults["conType"] = val
}
func getConTypeResult() -> String {
return theTestResults["conType"] ?? "Err"
}
}
测试 View .swift
var comResClass = complileResults()
class TestView: UIViewController, XMLParserDelegate {
override func viewDidLoad() {
super.viewDidLoad()
comResClass.setConTypeResult(val: "WiFi")
let ct = comResClass.getConTypeResult()
print("CT ", ct)
}
}
最佳答案
有一些方法可以做到这一点。
class complileResults {
var theTestResults : [String: String] = [
"conType": "",
"date": "",
"time": "",
"jitter": "",
"loss": "",
"dspeed": "",
"uspeed": "",
"delay": ""
]
}
class TestView: UIViewController, XMLParserDelegate {
let result = complileResults()
override func viewDidLoad() {
super.viewDidLoad()
result.theTestResults["conType"] = "WiFi"
print(result.theTestResults["conType"] ?? "Err")
}
}
或者这个更通用一些。
class orcomplileResults {
var theTestResults : [String: String] = [
"conType": "",
"date": "",
"time": "",
"jitter": "",
"loss": "",
"dspeed": "",
"uspeed": "",
"delay": ""
]
func setResult(key: String, value: String) {
theTestResults[key] = value
}
func getResult(key: String) -> String {
return (theTestResults[key] ?? "Err")
}
}
class orTestView: UIViewController, XMLParserDelegate {
let result = orcomplileResults()
override func viewDidLoad() {
super.viewDidLoad()
result.setResult(key: "conType", value: "WiFi")
print(result.getResult(key: "conType"))
}
}
关于ios - 从另一个类中的函数获取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56014936/