Swift libraries with Silver

This question is somewhat related to "pure" swift libraries for use with Silver

I wonder is there any way to use swift package system in silver?

I understand that it is impossible to use platform specific libraries.
But what about https://github.com/ReactiveX/RxSwift ?
Or even those demos https://swift.org/package-manager/#example-usage ?

With Xamarin I may just add/open any githhub library .sln - and I’m ready to go… Plus it have NuGet.
What about Silver? Swift have dependency manager too…

All in all - do you have plans to support swift package system?

1 Like

I think that’s something we’ll start worrying about when the thing goes beyond version 0.1 :wink:

Right now, our Swift compiler, for Cocoa, compiles for Cocoa, against the Objective-C runtime. You can use any C or Objective-C library, but we specifically do not support linking against libraries built with Apple Swift yet because (a) this specs for that have been out grand total of three or four weeks (if you want to call the compiler sourcecode specs :wink: and (b) are a moving target. Apple said their goal for Swift 3.0 is to finalize thew ABI and lock it down. Our plan it to start supporting linking against (and creating) “Apple Swift” binaries, once 3.0 is solid enough for that to be the case (i’m ghopoig around of after WWDC).

Things are a bit different t with Xamarin. Xamarin is .NET. So you cal always use any .NET library our there, just reference it and you’re done. Silver can also compile for .NET, and when you do, you can use any .NET library out there, same as with Xamarin (in fact, you can even use Silver with Xamarin). But Silver is also cross platform and compiles against native Cocoa (see above) and Java/JVM/Dalvik. You can’t just use .NET libraries there (but you can use any Java library, when building for Java, for example.

Does that make sense?

We’re looking into supporting package systems, in general. We doom support NuGet in VS, for .NET, and we recently dded support for Java one (Glade?) for the next release. We’re also looking at various options on the Cocoa front, but we’re nit committing to anything. When and if the Swift package manager becomes something solid that people use, we’ll look at supporting it.

Note that, regardless, support for package mangers is pretty orthogonal to whether nor not you an use third party libraries with the compiler.

That’s my point. You may have one shared library for all projects with .Net.
I not saying about use of .Net library for Windows, Java for Android, etc…
Exactly the same code across all platforms (if library platform agnostic).

I say - you have shared library in the Silver.
It just need some convenient way to load 3rd party swift library from GitHub there.
(And maybe it already is? - I just don’t know about it)

Well, I actually meant to compile code with YOUR compiler to target platform.
Make shared project. Load [somehow] swift code from library there. Use it from target project. Compile.

Problem in [somehow].

Well… It may be orthogonal to compiler… But I don’t think this is orthogonal to programmer.
How should I use 3rd party library with Silver?
Download source from GitHub, that add .swift files one by one into the shared project? :wink:

I mean - this is just a lack of mechanism to load/use 3rd party library. Or if it is not the case - then it is lack of documentation about this :).

I understand the situation with package/dependency managers.
Lets look on the problem from the other side:

In VS you may open only .sln projects.
All 3rd party swift libraries definitely not have .sln .
In most cases library is just a bunch of files in folders :slight_smile: [lets omit dependencies for now]
VS can’t open “folder as project”.

Ergo - there is no way to “import” swift library to Silver solution.
It would be OK, if there was a way to import folder to a Silver shared project.

Very interesting thread!
Anyways, supposed to have a Swift sources SDK that relies on let’s say Http stack (let’s say Alamofire - https://github.com/Alamofire/Alamofire), the first issue I see here is that this relies on Cocoa HTTP stack (Foundation’s NSURL stuff).
The same we can have with libraries like Crypto, that relies on the platform itself, let’s take this basic example here

import Foundation
import CryptoSwift

extension String {
    func aesEncrypt(key: String, iv: String) throws -> String{
        let data = self.dataUsingEncoding(NSUTF8StringEncoding)
        let enc = try AES(key: key, iv: iv, blockMode:.CBC).encrypt(data!.arrayOfBytes(), padding: PKCS7())
        let encData = NSData(bytes: enc, length: Int(enc.count))
        let base64String: String = encData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0));
        let result = String(base64String)
        return result
    func aesDecrypt(key: String, iv: String) throws -> String {
        let data = NSData(base64EncodedString: self, options: NSDataBase64DecodingOptions(rawValue: 0))
        let dec = try AES(key: key, iv: iv, blockMode:.CBC).decrypt(data!.arrayOfBytes(), padding: PKCS7())
        let decData = NSData(bytes: dec, length: Int(dec.count))
        let result = NSString(data: decData, encoding: NSUTF8StringEncoding)
        return String(result!)

(from: https://gist.github.com/yutelin/f4f66e0c78474db1de51)

Here you need NSData (so the binary data handlers) and its encoding/decoding counterparts:

base64EncodedStringWithOptions, NSDataBase64DecodingOptions

Also it relies on a cross platform AES crypt/decrypt lib - https://github.com/Pakhee/Cross-platform-AES-encryption.

Another examples could be done with XML / JSON Parsers made from the scratch (not relying on Cocoa libraries, but ISA only, etc.), they still need the Cocoa Foundation.

My last example was to have a Promise-like in Silver, that can be implemented using the language itself (pure Swift) for most of its patterns, and it’s quite like ready.

Nah, not all libraries have cocoa dependencies.
For example math/logic libraries - don’t.

import Darwin

Well, ok.
I agree - there is no way to use 3rd party shared libraries with Silver’s swift now.

That’s correct, unless someone does not port them to Silver, like Alamofire could be ported using Sugar Http stack.

Regarding JSON encoding/decoding Swift libraries without any external dependencies - apart Cocoa Foundation I want to point out here the following:

Himotoki - https://github.com/ikesyo/Himotoki
Argo - https://github.com/thoughtbot/Argo
ObjectMapper - https://github.com/Hearst-DD/ObjectMapper

All these libraries are pure Swift if we consider the only dependency by Foundation.
This implies Cocoa Data Types like (let’s consider Himotoki): NSDictionary, NSNull, NSNumber etc. With a bit of effort these dependencies could be wrapped or removed.

Sugar has ready-to-use support for JSON, as well.

Yes absolutely, the feature I was looking for was a Object Mapping like protocol.
Let’s take this

         let jsonCallback: HttpContentResponseBlock<Sugar.Json.JsonDocument!>! = { response in 
			if response.Success {
				var obj = response.Content.RootObject
		Http.ExecuteRequestAsJson( Url(url), jsonCallback)

If I have my custom Object to be mapped to a JSON object let’s say something like (taken from ObjectMapper library)

class User: Mappable {
    var username: String?
    var age: Int?
    var weight: Double!
    var array: [AnyObject]?
    var dictionary: [String : AnyObject] = [:]
    var bestFriend: User?                       // Nested User object
    var friends: [User]?                        // Array of Users
    var birthday: NSDate?

    required init?(_ map: Map) {


    // Mappable
    func mapping(map: Map) {
        username    <- map["username"]
        age         <- map["age"]
        weight      <- map["weight"]
        array       <- map["arr"]
        dictionary  <- map["dict"]
        bestFriend  <- map["best_friend"]
        friends     <- map["friends"]
        birthday    <- (map["birthday"], DateTransform())

I would like to serialize and deserialize this object starting from the response:

var obj = response.Content.RootObject

using Sugar.Json.JsonDocument

but - in this case - I have found no doc to handle this transformations.

In general, my question would be how to handle platforms data type like NSDictionary dependencies in pure Swift projects like those ones that do import Foundation.NSDictionary, etc.

To what exactly Type do you plan to map Foundation.NSDictionary ?

P.S. I think your question rather, how to use pure Swift projects without rewriting them for Silver :wink:

There’s Swift.Dictionary, aka [T:U], which maps to each platform’s “native” dictionary type…

1 Like

yeah and it’s easy as well to move from a data type to another mapping:

var swiftDict : Dictionary<String,AnyObject!> = Dictionary<String,AnyObject!>()
for key : AnyObject in ocDictionary.allKeys {
    let stringKey = key as String 
    if let keyValue = ocDictionary.valueForKey(stringKey){
        swiftDict[stringKey] = keyValue

So I think one could change the NSDictionary to Swift.Dictionary definitively, since mapping is 1:1.
What about NSNumber and NSNull instead, they are wrapper of Number and nil?

@mh Another question is, Sugar.Json is not automatically converted into native platform supported objects or the more closer object data type?
If I declare a method like

public func testGetJson(var url: String, success: (response:Sugar.Json.JsonObject?) ->(), error: (response:Exception?) ->() ) { //... }

The Objective-C automatic header will have a JsonObject in the mapped method declaration. Is that correct?

@mh Considering that Apple has started to provide Foundation as a Swift code base, so platform agnostic for core utilities, internationalization, and OS independence, could this be imported in Silver as a library?

Thank you.

Once their ABI stabilizes and we support consuming Swift libraries, yes. Note that their version of the library will probably never compile in Silver because it uses too much of their compiler magic, so it would still not be available on the other platforms, though. Only on Cocoa. Since they won’t be providing a library for .NET or Android, any time soon. ;). So. It much gained, for now, over just using the Foundation we already have from Cocoa :wink:

1 Like

@mh agreed, not sure about the dependencies, it should “provide a level of OS independence” according to Apple, but I understand that they are very far to this at this time. And according to them Foundation will run on Linux including NSString, NSDictionary, NSArray, and NSSet (that we discussed before in this thread) in order to have high level semantics in the language. The interesting thing can be synthesized here:

Why not make the existing Objective-C implementation of Foundation open source?

Foundation on Darwin is written primarily in Objective-C, and the Objective-C runtime is not part of the Swift open source project. CoreFoundation, however, is a portable C library and does not require the Objective-C runtime. It contains much of the behavior that is exposed via the Foundation API. Therefore, it is used on all platforms including Linux.

I’m pretty sure that Silver/RemObject contribution could be very important to make true portable libraries.

Yes, it’s OS independent in that it has re-implementartions of everything for each OS, where needed. So Apple provides a Foundation with #ifdefs for, say, Mac, iOS and Linux. But not for .NET and for Java/Android, so their Foundation can’t be sued on .NET and Java, for example. Also, their Foundation implementation (asm their Base Library) is very low-level and won’t compile in Silver, probably.

When compiled, and once we support swift libraries, Silver all be able to use it. But that requires a usable binary to exist to start with :wink:

Well, but that won’t give Silver any ground until Foundation and libdispatch will be ported to .NET and Java, and it does seem to happen anywhere soon. I mean, since Xamarin and RoboVM leverage existing .NET and Java ecosystem it is obviously way easier for them to serve their customer base. But since you guys are targeting Swift developers - the switching costs are very high, since Apple-Swift is 95% in-house yet and Silver doesn’t yet have a solid ecosystem, we need to port a lot of stuff to Sugar and implement many more core stuff our-selves, which arguably won’t decrease time-to-market comparing to having separate Java, Swift codebases. Code-sharing is the large benefit, but it is often seen through the prism of shorter time-to-market. I really appreciate what you guys did, Silver is really awesome and I love it but it needs strong community support to build a healthy-ecosystem so that it can fit enterprise requirements, which at least requires you guys to have some certain marketing strength in order to have more exposure, so that a force of community enthusiasts will at least know about how awesome your tools are.

Another thing that comes to mind is that it will be difficult to see any solid community-based development for Sugar since it written in Oxygen/Pascal and it cannot run on apple’s swift. The only chance I can see that swift community getting involved in building Silver ecosystem, if that base library would be different from Sugar and will be written in Swift/C++ that can run build on apple’s swift. Since the whole army of these hipsters will simply won’t switch from Apple’s Xcode. So you guys might consider this, I understand your intention to leverage Sugar, since it is proud baby of your Elements eco-system. I guess writing the base library that will run on apple’s swift might be a challenge since it will be way more troublesome fitting it to Java and .NET stuff that simply doesn’t exist in Swift, but this might be a necessary tradeoff to overcome, for example we recently saw great community support for https://github.com/PerfectlySoft/Perfect that does not have dependency on apple’s frameworks.

Totally agree with this.

  1. Few mobile development shops are going to give up XCode and native Apple swift on iOS & OSX, so interoperability with Apple Swift is really important.
  2. Once the package manager has useful stuff in it, then a silver implementation of Foundation, libdispatch, and XCTest will be crucial.
  3. Sugar is pretty much useless because you can’t use it in Apple Swift

Because of these points we invested in writing our own cross platform library, that works in both XCode & Fire/Silver/Android Studio. This doesn’t implement Foundation, but I’m beginning to think we should have.

I would love Silver to be the default Android impl of Swift, but it’s going to have to compete with the Android native port which is going on at the moment. That’s going to be super clunky to use as will compile to native code and be usable through JNI (ugh), but will be the default option for most people because it will be in the Apple swift code base, and it will have the linux ports of Foundation, libdispatch and XCTest to (partially) run on.