我是Swift程序员的开始。
以下代码似乎可以在Xcode 7.0 Playground中正常编译(没有可见的错误):
//: Playground - noun: a place where people can play
//#!/usr/bin/env xcrun swift
import WebKit
let application = NSApplication.sharedApplication()
application.setActivationPolicy(NSApplicationActivationPolicy.Regular)
let window = NSWindow()
window.setContentSize(NSSize(width:800, height:600))
window.styleMask = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask
window.center()
window.title = "Minimal Swift WebKit Browser"
window.makeKeyAndOrderFront(window)
class WindowDelegate: NSObject, NSWindowDelegate {
func windowWillClose(notification: NSNotification) {
NSApplication.sharedApplication().terminate(0)
}
}
let windowDelegate = WindowDelegate()
window.delegate = windowDelegate
class ApplicationDelegate: NSObject, NSApplicationDelegate {
var _window: NSWindow
init(window: NSWindow) {
self._window = window
}
func applicationDidFinishLaunching(notification: NSNotification) {
let webView = WebView(frame: self._window.contentView!.frame)
self._window.contentView!.addSubview(webView)
webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.apple.com")!))
}
}
将完全相同的代码粘贴到" AppDelegate.swift" OSX的新Cocoa应用程序的文件,我得到7个错误,完全相同:"顶级不允许表达式#34;。
通过搜索,我推断出Playground允许普通项目没有发生错误并且错误正在发生,因为表达式是在类或实例方法之外的#34;。
但是,我不确定如何修改程序才能正确构建。
答案 0 :(得分:1)
是的,普通项目不允许顶层代码,因为它没有明显的运行时间。您需要确定何时应运行激活策略和窗口/委托代码(即,将该代码移动到方法内)。我建议applicationDidFinishLaunching(_:)
,因为它是在您的应用完成启动时调用的,并且是进行此类设置的常见位置。完成的代码将为:
import WebKit
class WindowDelegate: NSObject, NSWindowDelegate {
func windowWillClose(notification: NSNotification) {
NSApplication.sharedApplication().terminate(0)
}
}
class ApplicationDelegate: NSObject, NSApplicationDelegate {
var _window: NSWindow
init(window: NSWindow) {
self._window = window
}
func applicationDidFinishLaunching(notification: NSNotification) {
let webView = WebView(frame: self._window.contentView!.frame)
self._window.contentView!.addSubview(webView)
webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.apple.com")!))
let application = NSApplication.sharedApplication()
application.setActivationPolicy(NSApplicationActivationPolicy.Regular)
let window = NSWindow()
window.setContentSize(NSSize(width:800, height:600))
window.styleMask = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask
window.center()
window.title = "Minimal Swift WebKit Browser"
window.makeKeyAndOrderFront(window)
let windowDelegate = WindowDelegate()
window.delegate = windowDelegate
}
}