首页 > 解决方案 > AppleScript 记录到 Swift 数组(或更好)的列表

问题描述

我基于这个示例测试了一个小 OSX 应用程序,它使用 AppleScript 的桥接从 iTunes 获取简单信息。

就像我在 ComboDrums 的评论(是我)中所说的那样,我有一个脚本可以将我所有的 iTunes 播放列表放在树中,但是一旦返回比简单的字符串更复杂,它就会失败。

所以我正在寻找将 AppleScript 的列表转换为 Swift 友好对象的方法。

任何想法 ?

谢谢。

脚本:

to getStaticPlaylistsTree()
    tell application "iTunes"
        set theList to {{theName:"Bibliothèque", theID:"66270731FDBE2C50", isFolder:false, theClass:library playlist, isSmart:false, theCount:37581}, {theName:"Clips vidéo", theID:"07D5032B96891D67", isFolder:false, theClass:user playlist, isSmart:true, theCount:283}}
    end tell
    return theList
end getStaticPlaylistsTree

标签: arraysswiftmacosapplescriptitunes

解决方案


首先,使用以 NSDictionary 作为参数的构造函数创建 swift 类或结构

struct SwiftModel {

    // Declare attributes

    init(dictionary: NSDictionary) {
        self.isFolder = dictionary.value(forKey: "isFolder") as! Bool
        self.isSmart = dictionary.value(forKey: "isSmart") as! Bool
        self.theCount = dictionary.value(forKey: "theCount") as? Int
        self.theID = dictionary.value(forKey: "theID") as? String
        self.theName = dictionary.value(forKey: "theName") as? String
        self.theClass = (dictionary.value(forKey: "theClass") as? NSAppleEventDescriptor)
    }
}

然后,使用 flatMap 或 compactMap 将苹果脚本列表转换为 Swift Array。

let listFromAppleScript = // List returned from apple script i.e self.iTunesBridge.getStaticPlaylistsTree
let staticPlayListTree = listFromAppleScript?.compactMap({SwiftModel(dictionary: $0 as! NSDictionary)})
print(staticPlayListTree![0].theName)

输出:可选(“Bibliothèque”)


推荐阅读