简体   繁体   English

复杂线警告:AnyObject不是NSObject的子类型

[英]Complex line warns: AnyObject is not a subtype of NSObject

I'm trying to convert the following code into Swift 3. Its purpose is to print the cellular signal strength to the console. 我正在尝试将以下代码转换为Swift 3.其目的是将蜂窝信号强度打印到控制台。 The StackOverflow post this came from can be found here . 这个来自的StackOverflow帖子可以在这里找到。

UIApplication *app = [UIApplication sharedApplication];
NSArray *subviews = [[[app valueForKey:@"statusBar"]     valueForKey:@"foregroundView"] subviews];
NSString *dataNetworkItemView = nil;
for (id subview in subviews) {
    if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarSignalStrengthItemView") class]])
    {
        dataNetworkItemView = subview;
        break;
    }
}
int signalStrength = [[dataNetworkItemView valueForKey:@"signalStrengthRaw"] intValue];
NSLog(@"signal %d", signalStrength);

And, after my own attempts (swift is new to me), some online converters, and Xcode's automatic conversion from Swift 2.2 to 3, i'm stuck with two issues. 而且,在我自己的尝试(对我来说很快),一些在线转换器,以及Xcode从Swift 2.2到3的自动转换之后,我遇到了两个问题。 Here is the current problematic code: 这是当前有问题的代码:

let app = UIApplication.shared
let subviews: NSArray = (((app.value(forKey: "statusBar"))! as AnyObject).value(forKey: "foregroundView"))!.subviews
var dataNetworkItemView: NSString?
for subview in subviews {
    if (subview as AnyObject).isKind(of: NSClassFromString("UIStatusBarSignalStrengthItemView")!) {
        dataNetworkItemView = subview as? String as NSString?
        break
    }
}
let signalStrength = Int(((dataNetworkItemView!.value(forKey: "signalStrengthRaw") as! String) as NSString ?? "0").intValue)
print("signal \(signalStrength)")

The second line (let subviews: ...) throws the error: 第二行(让子视图:...)抛出错误:

'(AnyObject)' is not a subtype of 'NSObject'

and the second to last line (let signalStrength = ...) throws the following warning: 并且倒数第二行(让signalStrength = ...)抛出以下警告:

Left side of nil coalescing operator '??' has non-optional type 'NSString' so the right side is never used

The second issue makes more sense to me than the first, but how can I go about fixing the actual error? 第二个问题对我来说比第一个问题更有意义,但我怎样才能修复实际错误? I'm not intending to be spoon-fed code but rather am trying to figure out why the error exists and what would satisfy the error and produce the desired results. 我不打算用勺子代码,而是试图弄清楚为什么错误存在以及什么会满足错误并产生预期的结果。 Thanks :) 谢谢 :)

idk if it works for you. idk如果它适合你。 but i was having same issue and it works for me try using NSArray instead of AnyObject 但我有同样的问题,它适用于我尝试使用NSArray而不是AnyObject

let subviews: NSArray = (((app.value(forKey: "statusBar"))! as NSArray).value(forKey: "foregroundView"))!.subviews
var dataNetworkItemView: NSString?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM