macOs Swift命令行应用程序在执行任务语句时崩溃

axr492tv  于 2023-01-25  发布在  Swift
关注(0)|答案(1)|浏览(143)

我正在尝试一个简单的练习来演示如何在Swift中使用async/await,并且尽我所能隔离,应用在执行Task语句时崩溃。我尝试过在抛出和捕获时捕获异常,但调用堆栈没有提供任何额外的问题洞察力。错误发生在线程1:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)

我的理论是命令行模板不支持这种简单形式的任务。

//
//  main.swift
//

import Foundation

struct User {
    var username: String
    var movies = [Movie]()
}

struct Movie {
    var title: String
    var rating: Double?
}

class ManagerUsingAsync {
    func getUsers() async throws -> [User] {
        let allIsGood = true // Bool.random()

        if allIsGood {
            let users = ["mary", "casey", "theo", "dick"].map { User(username: $0) }
             return users
        } else {
            throw URLError(.cannotConnectToHost)
        }
    }

    func getUsersMovies(username: String) async throws -> [Movie] {
        let allIsGood = true // Bool.random()

        if allIsGood {
            let movies = ["breaking away", "diner", "the great escape"].map { Movie(title: $0) }
            return movies
        } else {
            throw URLError(.cannotCreateFile)
        }
    }

    func getMovieRating(title: String) async -> Double? {
        let allIsGood = true // Bool.random()

        if allIsGood {
            return Double.random(in: 1...10)
        }

        return nil
    }
}


func testAsync() async -> [User] {
    var _users = [User]()
    let manager = ManagerUsingAsync()

    do {
        _users = try await manager.getUsers()
        for var user in _users {
            user.movies = try await manager.getUsersMovies(username: user.username)
            for var movie in user.movies {
                movie.rating = await manager.getMovieRating(title: movie.title)
            }
        }

    } catch (let error) {
        print(error.localizedDescription)
    }

    return _users
}

print("TEST ASYNC/AWAIT...")

Task {
    let users = await testAsync()
    for user in users {
        print( "Username: \(user.username) Movies: \(user.movies)" )
    }
}
bvk5enib

bvk5enib1#

显然,这与我的公司MacBook是如何被锁定的有关。我无法更深入地了解这一点,但同样的代码在我的个人MacBook上运行良好(正如评论中分享的@RobNapier)。
不确定这个Q是否应该被撤回,但是关于企业MDM对开发人员的影响,有一些东西需要了解(不是第一次)。

相关问题