Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import library into swift code used in CLI?

What I want to do

I want to try to get son file through API by swift library on CLI. I am using the library, Alamofire, but I can't understand how to import swift library.

Maybe some tasks are needed before import (building? linking?) but I can't find how to document... Could you teach me how to do it?

Problem

$ swift getAPI.swift
getAPI.swift:1:8: error: no such module 'Alamofire'
import Alamofire
       ^

Sourcecode

import Alamofire

func getArticles(){
  Alamofire.request(.GET, "https://qiita.com/api/v2/items")
    .responseJSON { response in
      print(response.result.value )
    }
}

getArticles()
like image 932
hiroga Avatar asked Dec 13 '22 23:12

hiroga


1 Answers

This should help with running one-off scripts and when using the Swift REPL. However, for building simple tools for the command line, I would recommend using the Swift Package Manager since it takes care of the linking and dependency management for you.


To link your script code to the Alamofire library, the swift compiler has to know where to the library is located. By default it searches /Library/Frameworks, but we can supply options to tell it where else to look. Checking swift --help, we see the following options (among many others).

USAGE: swift [options] <inputs>

OPTIONS:
  -F <value>    Add directory to framework search path
  -I <value>    Add directory to the import search path
  -L <value>    Add directory to library link search path

The directory you supply must to contain the compiled binaries of the libraries you want to import.

  • To import .swiftmodule binaries, use -I
  • To import .framework binaries, use -F
  • For linking to libraries like libsqlite3.0.dylib, use -L

I think Carthage and CocoaPods will build frameworks, whereas the Swift Package Manager will build .swiftmodules. All three should put the binaries in very predictable locations. Different kinds of binaries may all be in the same and that's okay.

Putting it all together, if you build with SPM, your invocation might look like this:

$ swift -I .build/debug/

But if you manage dependencies with Carthage, it might look something like this:

$ swift -F ./Carthage/Build/iOS

For further reading, I found these resources useful:

  • krakendev.io/blog/scripting-in-swift
  • realm.io/news/swift-scripting/

Update: The Swift package manager can now take care of this for you as well! If you're writing a script as a package and include a bunch of dependencies, like Alamofire, you can now test them out in the REPL. Just cd into your package directory and launch it using swift run --repl. See the swift.org blog for more details.

like image 50
mklbtz Avatar answered Dec 16 '22 14:12

mklbtz