add a dependency to a binarytarget in a package.swift file in swift

To add a dependency to a binary target in a package.swift file in Swift, you must:

  1. Declare the dependency in the Package dependency array using its package name and the minimum version required:

    main.swift
    let package = Package(
        name: "MyPackage",
        products: [...],
        dependencies: [
            .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.0")
        ],
        targets: [...]
    )
    
    198 chars
    9 lines
  2. Add the dependency package as a target dependency to each binary target that needs it:

    main.swift
     .binaryTarget(
         name: "MyBinaryTarget",
         path: "Sources/MyBinaryTarget",
         dependencies: [
             "Alamofire"
         ]
     ),
    
    135 chars
    8 lines

The dependencies parameter of the binaryTarget method allows specifying an array of target dependencies by using its target name.

If the dependency package also defines binary targets, you can use product(name:) instead of target(name:) to declare the dependency using the name of the product generated by the other package.

gistlibby LogSnag