我正在尝试将以下代码转换为Swift 3.其目的是将蜂窝信号强度打印到控制台。可以找到来自的StackOverflow帖子here。
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);
而且,在我自己的尝试(对我来说很快),一些在线转换器,以及Xcode从Swift 2.2到3的自动转换之后,我遇到了两个问题。这是当前有问题的代码:
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)")
第二行(让子视图:...)抛出错误:
'(AnyObject)' is not a subtype of 'NSObject'
和倒数第二行(让signalStrength = ...)抛出以下警告:
Left side of nil coalescing operator '??' has non-optional type 'NSString' so the right side is never used
第二个问题对我来说比第一个问题更有意义,但我怎样才能修复实际错误?我不打算用勺子代码,而是试图弄清楚为什么错误存在以及什么会满足错误并产生预期的结果。谢谢:))
答案 0 :(得分:0)
idk如果适合你。但我有同样的问题,它对我有用 尝试使用 NSArray 而不是 AnyObject
let subviews: NSArray = (((app.value(forKey: "statusBar"))! as NSArray).value(forKey: "foregroundView"))!.subviews
var dataNetworkItemView: NSString?