SwiftPlayground-Pharo: Interact with Swift on Pharo

栏目: IT技术 · 发布时间: 4年前

内容简介:Because of Xcode Swift PlaygroundRun Swift with the Pharo Swift Playground, interoperate with Pharo, inspect output and Swift

Never ever praise an Xcode playground. It’s bound to crash 10 seconds later. #Swift #xcode #ios

— YOAD (@YOADAPPS) December 20, 2018

Now I get why Apple requires students to submit a playground that can be experienced in at most 3 minutes to apply for a WWDC scholarship… The reviewers have to spend the remaining 57 minutes trying to get Xcode to run it successfully

— Patrick Balestra (@BalestraPatrick) March 24, 2019

Because of Xcode Swift Playground instability while running even the simplest of Swift code, this Swift code runner was implemented with Pharo. It brings the benefits of greatly increased stability for trying short pieces of code and working with Swift output in the powerful Pharo environment. This is a work in progress.

SwiftPlayground-Pharo

Interact with Swift on Pharo.

Run Swift with the Pharo Swift Playground, interoperate with Pharo, inspect output and Swift ASTs .

  • Pharo 7.0 reference platform.
  • Requires macOS 10.14.5 (or later) or GNU/Linux (tested with Ubuntu 14.04, 64 bit).

SwiftPlayground-Pharo: Interact with Swift on Pharo

Table of Contents

Installation

  1. Install and setup the Swift tools for your environment:

  2. In a Playground, evaluate:

    Metacello new
      repository: 'github://brackendev/SwiftPlayground-Pharo';
      baseline: 'SwiftPlayground';
      onConflict: [ :ex | ex useIncoming ];
      onUpgrade: [ :ex | ex useIncoming ];
      onDowngrade: [ :ex | ex useLoaded ];
      ignoreImage;
      load.

Usage

SWIFT PLAYGROUND

Write, compile, run, and inspect output of Swift code via the Swift Playground (accessible via the Tools menu).

SwiftPlayground-Pharo: Interact with Swift on Pharo

SwiftPlayground-Pharo: Interact with Swift on Pharo

Important contextual menu items:

  • Do it – Compile and run the selected Swift code
  • Inspect it – Compile and run the selected Swift code, inspect it
  • Print it – Compile and run the selected Swift code, print it ( TODO )

Additionally, the contextual menu item, Inspect AST , returns the Swift AST for the selected Swift code. For example, print("Hello, World!") returns:

(import_decl range=[Swift:1:1 - line:1:8] 'Foundation')
  (top_level_code_decl range=[Swift:2:1 - line:2:22]
    (brace_stmt range=[Swift:2:1 - line:2:22]
      (call_expr type='<null>' arg_labels=_:
        (unresolved_decl_ref_expr type='<null>' name=print function_ref=unapplied)
        (paren_expr type='<null>'
          (string_literal_expr type='<null>' encoding=utf8 value="Hello, World!" builtin_initializer=**NULL** initializer=**NULL**)))))

INLINE SWIFT

Outside of the Swift Playground, Swift code can be executed within Pharo code by using the runSwift string class extension. For example:

SwiftPlayground-Pharo: Interact with Swift on Pharo

API Reference

SWIFT OUTPUT AND ABSTRACT SYNTAX TREES

Pharo class extension methods can be used to compile, run, and view the AST of Swift code.

◼︎ String class extension: runSwift

Returns a string representation of a Swift object from Swift code. Use Swift's print function within the Swift code for output to Pharo. For example:

swiftString := 'The five boxing wizards jump quickly' asLowercase asSwiftString.
('let (lowercased, alphabet) = (Set(', swiftString, '), "abcdefghijklmnopqrstuvwxyz")
print("\(!alphabet.contains { !lowercased.contains($0) })")') runSwift.
"Returns 'true'"

Tip: Simple Swift code does not require Swift's print function. For example:

'Array("ABCDE")' runSwift.
"Returns '["A", "B", "C", "D", "E"]'"
swiftArray := #(1 2 3 4 5) asSwiftArray.
(swiftArray, '.map{$0 * $0}.reduce(0, +)') runSwift.
"Returns '55'"

◼︎ String class extension: swiftAST

Returns the Swift AST of Swift code.

PHARO OBJECT TO SWIFT STRING SERIALIZATION

Pharo class extension methods can be used as quick helpers to serialize Pharo objects to Swift psuedo-objects (string representations of Swift objects). For example, 'Hello, World!' asSwiftString returns '"Hello, World!"' .

In the code below, notice the usage of sentence , asSwiftString , and the swiftCode string concatenation:

sentence := 'The five boxing wizards jump quickly' asLowercase asSwiftString.
swiftCode := ('
// Determine a pangram
let (sentenceSet, alphabet) = (Set(', sentence, '), "abcdefghijklmnopqrstuvwxyz")
print(!alphabet.contains {
  !sentenceSet.contains($0)
})
').
swiftCode runSwift.
"Returns 'true'"

The following extension methods have been implemented (with examples). The examples are also availabe via the SPExamples object.

◼︎ Array class extension: asSwiftArray

Returns a string representation of a Swift object. Currently only handles one depth of booleans, numbers, and strings.

#(1 'A' 2 true 3 false) asSwiftArray.
"Returns '[1,"A",2,true,3,false]'"

◼︎ Boolean class extension: asSwiftBoolean

Returns a string representation of a Swift object.

true asSwiftBoolean.
"Returns 'true'"

◼︎ Dictionary class extension: asSwiftDictionary

Returns a string representation of a Swift object. Currently only handles one depth of booleans, numbers, and strings.

(Dictionary newFrom: {(1 -> 2). ('A' -> 3). (4 -> 'B'). (5 -> true). (false -> 'C'). ('D' -> 'E')})  asSwiftDictionary.
"Returns '[1:2,"A":3,4:"B",5:true,"D":"E",false:"C"]'"

◼︎ String class extension: asSwiftString

Returns a string representation of a Swift object.

'Hello, World!' asSwiftString.
"Returns '"Hello, World!"'"

SWIFT RESPONSE STRING TO PHARO OBJECT DESERIALIZATION

(TODO)

IMPORTS

The Apple Foundation framework is imported into Swift code automatically. To use other Apple frameworks with Swift code, use the Swift import directive as needed.

ASYNCHRONOUS SWIFT CODE

To prevent asynchronous Swift code from exiting too early, use the Swift dispatchMain() function to never return and use the Swift exit() function to exit where appropriate.

For example, in the Swift code below, a Swift URLRequest network request session is started and dispatchMain() is called so the program does not prematurely exit. In the session response closure, exit(0) is then called to exit the program.

let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)

var url = URL(string: "https://www.gravatar.com/4f64c9f81bb0d4ee969aaf7b4a5a6f40.json")
var request = URLRequest(url: url!)
request.httpMethod = "GET"

let task = session.dataTask(with: request, completionHandler: { data, response, error in
    if let uError = error {
        print(uError.localizedDescription) // Returns error string
    } else if let uData = data, let string = String(data: uData, encoding: String.Encoding.utf8) {
        print(string) // Returns response string
    }
    exit(0) // Exit after asynchronous work is complete
})
task.resume()

session.finishTasksAndInvalidate()
dispatchMain() // Prevent premature exit

TODO

  • Swift Playground Print it
  • Swift Playground syntax highlighting and code completion
  • Swift Playground open/save files
  • Swift response string to Pharo object deserialization
  • Move documentation to the wiki
  • Move to Spec2

Acknowledgements

This project makes use of the following third-party library:

Author

brackendev

License

SwiftPlayground-Pharo is released under the MIT license. See the LICENSE file for more info.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

我是一只IT小小鸟

我是一只IT小小鸟

胡江堂、李成、唐雅薇、秦琴、蒋宇东、刘未鹏、居振梁、刘帅、温卫斌、张弦、张凯峰、庄表伟、宋劲杉、程露、黄小明、易晓东、简朝阳、林健、高昂、徐宥、辜新星 / 电子工业出版社 / 2009 / 29.80

一群IT小小鸟—— 来自十几所院校,或男生,或女生;或科班,或半路转行。 分布在不同的公司,或外企,或国企,或民企,老板有土有洋。 有失意,有快意;有泪水,有欢笑。在失望中追求希望,在迷茫中辨别方向。 他们用自己的成长故事,告诉在校的师弟师妹们: 青春太宝贵,千万别浪费;要想不浪费,万事早准备。一起来看看 《我是一只IT小小鸟》 这本书的介绍吧!

html转js在线工具
html转js在线工具

html转js在线工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具