Swift 协议 属性 检查是否弱
Swift protocol property check if weak
是否可以在 XCTest 中测试 class 属性 是否弱。
class A {
weak var p: String? = nil
}
结果: if p 属性 of a class is weak then assert
您可以使用这样的方法:
class TestObject {}
protocol A {
var a: TestObject? { get set }
}
class B: A {
var a: TestObject?
}
class C: A {
weak var a: TestObject?
}
func addVar(to: A) {
var target = to
target.a = TestObject() // Once we leave the scope of this function, the TestObject instance created here will be released unless retained by target
}
let b = B()
let c = C()
addVar(to: b)
addVar(to: c)
print(b.a) // prints Optional(TestObject) because class C uses a strong var for a
print(c.a) // prints nil because class B uses a weak var for a
转换为测试用例,它可能类似于:
func testNotWeak() {
func addVar(to: A) {
var target = to
target.a = TestObject() // Once we leave the scope of this function, the TestObject instance created here will be released unless retained by target
}
let testClass = B()
addVar(to: testClass)
XCTAssertNotNil(testClass.a)
}
是否可以在 XCTest 中测试 class 属性 是否弱。
class A {
weak var p: String? = nil
}
结果: if p 属性 of a class is weak then assert
您可以使用这样的方法:
class TestObject {}
protocol A {
var a: TestObject? { get set }
}
class B: A {
var a: TestObject?
}
class C: A {
weak var a: TestObject?
}
func addVar(to: A) {
var target = to
target.a = TestObject() // Once we leave the scope of this function, the TestObject instance created here will be released unless retained by target
}
let b = B()
let c = C()
addVar(to: b)
addVar(to: c)
print(b.a) // prints Optional(TestObject) because class C uses a strong var for a
print(c.a) // prints nil because class B uses a weak var for a
转换为测试用例,它可能类似于:
func testNotWeak() {
func addVar(to: A) {
var target = to
target.a = TestObject() // Once we leave the scope of this function, the TestObject instance created here will be released unless retained by target
}
let testClass = B()
addVar(to: testClass)
XCTAssertNotNil(testClass.a)
}