How do I import a swift function declared in a compiled .swiftmodule into another swift file?

前端 未结 3 731
死守一世寂寞
死守一世寂寞 2020-12-15 20:40

Is there a way to declare a function in a .swift file (that is compiled into a .swiftmodule), like so:

hello.swift

func hello_world() {
    println(\         


        
3条回答
  •  旧巷少年郎
    2020-12-15 20:59

    The .swiftmodule describes the Swift module's interface but it does not contain the module's implementation. A library or set of object files is still required to link your application against. Here's a modified version of the makefile that creates both libhello.dylib and hello.swiftmodule and builds the application against them:

    PWD=$(shell pwd)
    APP_NAME=main
    MODULE_NAME=hello
    LIB_NAME=lib$(MODULE_NAME).dylib
    LIB_PATH=$(PWD)/$(LIB_NAME)
    SWIFT_MODULE_PATH=$(PWD)/$(MODULE_NAME).swiftmodule
    
    main : clean
        xcrun swift \
            -emit-library \
            -o $(LIB_PATH) \
            -Xlinker -install_name \
            -Xlinker @rpath/$(LIB_NAME) \
            -emit-module \
            -emit-module-path $(SWIFT_MODULE_PATH) \
            -module-name $(MODULE_NAME) \
            -module-link-name $(MODULE_NAME) \
            -v \
            $(MODULE_NAME).swift
        xcrun swift $(APP_NAME).swift \
            -o $(APP_NAME) \
            -I $(PWD) \
            -L $(PWD) \
            -Xlinker -rpath \
            -Xlinker @executable_path/ \
            -v
    
    
    clean :
        rm -rf $(APP_NAME) $(LIB_NAME) $(MODULE_NAME).swiftmodule $(MODULE_NAME).swiftdoc
    

    In the absence of documentation I can't say that this is entirely correct, but it works.

    Note that if you simply want to use multiple source files within your application module this is much more straightforward and requires no import declaration or module qualification in main.swift:

    swift -o main hello.swift main.swift
    

提交回复
热议问题