Objective-C에서 호출하는 방법을 테스트하기 위해 Swift에서 두 가지 다른 함수를 정의했습니다. 그중 하나는 작동하고 다른 하나는 작동하지 않습니다!
여기에 정의했습니다.
public extension UIViewController {
func testAddingOperationTo(array: inout [Operation]) -> Operation {
let completionBlock = BlockOperation (block: {
print("completionOperation")
})
return completionBlock;
}
func testSomethingWith (count: Int){
print("testing something \(count)")
}
}
Objective-C에서 올바른 헤더 파일을 가져 왔고 두 번째 메서드를 잘 호출 할 수 있습니다.
[self testSomethingWithCount:0];
그러나 첫 번째는 작동하지 않습니다 ... Xcode 자동 완성에 표시되지 않으며 수동으로 입력하더라도 빌드 오류가 발생합니다. 나는 이것을 다음과 같이 부르고 싶다.
NSOperation *completionOperation = [self testAddingOperationToArray: operationsList];
여기서 무엇이 잘못 되었습니까? 함수를 잘못 정의했거나 내가 모르는 Swift에 대한 모호한 규칙이 있습니까?
@objc
Objective-C의 메서드를 사용하고 싶다고 Swift 컴파일러에 알리기 위해 메서드 선언 앞에 넣을 수 있습니다 . 다른 효과 중에서도 어떤 이유로 인해 Objective-C에서 메서드를 호출 할 수없는 경우 컴파일러에서 오류가 발생합니다.
@objc func testAddingOperationTo(array: [Operation]) -> Operation {
// Method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C
컴파일러가 어떤 매개 변수의 유형이 표시되지 않는지 알려 주면 좋겠지 만 Xcode 9 베타 2에서는 그렇지 않습니다.
어쨌든이 경우의 문제 inout
는 Objective-C에서 Swift 매개 변수를 표현할 수 없다는 것입니다. 매개 변수가 필요하지 않은 경우 inout
해당 키워드를 제거하면 메서드가 Objective-C에 연결됩니다.
함수가 수정할 수있는 배열을 전달해야하는 경우 한 가지 방법은 NSMutableArray
. 두 번째 버전은 Objective-C에 연결됩니다.
func testAddingOperation(to array: inout [Operation]) {
let completionBlock = BlockOperation (block: {
print("completionOperation")
})
array.append(completionBlock)
}
@objc func testAddingOperation(toOperations mutableArray: NSMutableArray) {
var array = mutableArray.map({ $0 as! Operation })
testAddingOperation(to: &array)
mutableArray.replaceObjects(in: NSRange(location: 0, length: mutableArray.count), withObjectsFrom: array)
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다