Expressions Are Not Allowed at The Top Level

Expressions are not allowed at the top level' if the module is not main.swift

Apparently yes, as per this answer. However, there are no citations as to this behaviour.

Update
This is documented on the Swift blog:

... earlier we said top-level code isn’t allowed in most of your app’s source files. The exception is a special file named “main.swift”, which behaves much like a playground file, but is built with your app’s source code. The “main.swift” file can contain top-level code, and the order-dependent rules apply as well. In effect, the first line of code to run in “main.swift” is implicitly defined as the main entrypoint for the program. This allows the minimal Swift program to be a single line — as long as that line is in “main.swift”.

Swift Playground Expressions are not allowed at the top level

You can try using class

like this:

struct Dummy: Decodable {
let userId: Int
let id: Int
let title: String?
let body: String?
}

final class APIHandler{

static let shared = APIHandler()
private init () {}

func get<T: Decodable>(_ type: T.Type, completion:@escaping (Result<T,Error>)->Void) {

guard let url = URL(string:"https://jsonplaceholder.typicode.com/posts" ) else {return}

let task = URLSession.shared
task.dataTask(with: url) { data, response, error in

if let error = error {
completion(.failure(error))
}

if let data = data {

do {
let json = try JSONDecoder().decode(T.self, from: data)
completion(.success(json))
} catch let error {
print("Error with Data : \(error)")
completion(.failure(error))
}

}

}.resume()

}
}

and test it:

APIHandler.shared.get([Dummy].self) { result in
switch result {
case .success(let res):
print("response: ", res)
case .failure(let error):
print(error)
}
}

Expressions are not allowed at the top level when writing in ContentView.swift

Assuming that you are trying to place this code inside the struct MyView..., the error message tells you what your problem is. You can't have expressions ("code") at that level. You can only have property declarations.

You can achieve what you want by using a closure;

let dmmmyyyyDateFormatter: DateFormatter = {
let df = DateFormatter()
df.dateFormat = "d MMM yyyy"
return df
}()

This executes the closure (which returns the object you are after) and assigns it to the property. Since the expressions are hidden are inside the closure, the compiler is happy as it has a context for executing the code.

Expression are not allowed at top level in function call of a class in Swift

You trying to typing code outside of class. You need to put it in you class and enclose in function body. Please take a look at my solution:

import UIKit
import Foundation

class BaseLabel:UILabel
{
func setFontAndTitle(FontName:String,FontSize:CGFloat,Title:String) {
self.font = UIFont(name: FontName, size: FontSize)
self.text = Title
}

func changePropertiesOfLabel(){
var lbl = BaseLabel()
lbl.setFontAndTitle ("Areal", FontSize: 14, Title: "Check label")
}

}

Expressions are not allowed at the top level

Yes, normal projects do not allow code at the top level, because there is no obvious time for it to run. You need to decide when your activation policy and window/delegate code should run (that is, move that code inside of a method). I suggest applicationDidFinishLaunching(_:), as it is called when your app is finished launching and is a common place to do this kind of setup. The finished code would read:

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
}
}

Expression are not allowed at the top level

Those three lines at the end of the code need to be somewhere else, such as a method in a class. The exception to this is if you're using a playground, which I expect is what you want to do in this case – playgrounds can have loose code just fine.

If you want to put it inside a class, use something like this:

class Testy {
func doStuff() {
let test = Square(sideLength: 5.2, name: "my test square")
let a = test.area()
print(a)
}
}

If you want to call it from an existing method, try using something like viewDidLoad() in a view controller.

Class Array Error - Expressions are not allowed at the top level

Statements like arr.append(user1Detail) can only go in closures (which includes methods, functions, initialisers, etc). Declarations can go in a class or the global level.

Your file can look like this:

class StudentDetail {

//Create Student Properties
var n: String?
var s: String?
var g: String?

//Initialise Properties
init(name: String, subject: String, grade: String) {
self.n = name
self.s = subject
self.g = grade
}

}

class ViewController: UIViewController {
let user1Detail = StudentDetail(name: "Koester", subject: "Science", grade: "9A")
let user2Detail = StudentDetail(name: "Tilly", subject: "Math", grade: "9A")

let people = [user1Detail, user2Detail]
var arr = [StudentDetail]()

override func viewDidLoad() {
arr.append(user1Detail) // now this is in a method
arr.append(user2Detail)
}
}

Expressions are not allowed at the top level when creating a dictionary in Swift

You can't do this, because Swift doesn't know when to execute this statement. Imagine, if you have a number of different Swift files and in each you have one expression or assignment. How would the system know which one it should execute first?
You can declare global variables, but then you must always provide an initializer (for example like dasblinkenlight's comment). Of course you can later modify the value of the variable from within any function.



Related Topics



Leave a reply



Submit