Gre*_*son 10 iphone objective-c ios swift ios8
只想阅读Swift中的启动选项.
这是我的旧obj-C代码,工作正常:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURL *URL = [launchOptions valueForKey:UIApplicationLaunchOptionsURLKey];
if (URL)
Run Code Online (Sandbox Code Playgroud)
这就是我认为Swift代码应该是这样的:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
if let options = launchOptions
{
let URL: NSURL = options(UIApplicationLaunchOptionsURLKey) as String
Run Code Online (Sandbox Code Playgroud)
但它给出了错误:
'(NSString!) - > $ T2'与'[NSObject:AnyObject]'不同
出现错误?但难以正确地投射它并且找不到如何做的链接.
vac*_*ama 29
斯威夫特3:
在Swift 3中,launchOptions是一个类型的字典[UIApplicationLaunchOptionsKey: Any]?,所以你可以像这样访问值:
launchOptions?[UIApplicationLaunchOptionsKey.url]
Run Code Online (Sandbox Code Playgroud)
由于键类型是UIApplicationLaunchOptionsKey,您可以enum简单地将类型缩写为.url:
launchOptions?[.url]
Run Code Online (Sandbox Code Playgroud)
与该键关联的值是a URL,而不是a String.此外,键可能不存在于字典中,因此您应该使用条件转换as?而不是正常转换.
在Swift中,您想要:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let url = launchOptions?[.url] as? URL {
// If we get here, we know launchOptions is not nil, we know
// key .url was in the launchOptions dictionary, and we know
// that the type of the launchOptions was correctly identified
// as URL. At this point, url has the type URL and is ready to use.
}
Run Code Online (Sandbox Code Playgroud)
斯威夫特2:
在你的代码中,launchOptions是一个类型的字典[NSObject: AnyObject]?,所以你想要访问这样的值:
options?[UIApplicationLaunchOptionsURLKey]
Run Code Online (Sandbox Code Playgroud)
与该键关联的值是a NSURL,而不是a String.此外,键可能不存在于字典中,因此您应该使用条件转换as?而不是正常转换.
在Swift中,您想要:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
if let url = launchOptions?[UIApplicationLaunchOptionsURLKey] as? NSURL {
// If we get here, we know launchOptions is not nil, we know
// UIApplicationLaunchOptionsURLKey was in the launchOptions
// dictionary, and we know that the type of the launchOptions
// was correctly identified as NSURL. At this point, url has
// the type NSURL and is ready to use.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6270 次 |
| 最近记录: |