Library for swiftly working with EOSIO blockchains on MacOS, Linux and iOS.
import EOSIOimport FoundationstructMyAction:ABICodable,Equatable{letmessage:String // most native types conform to ABICodableletfrom:Name // all eosio builtins have their own typelettip:Asset? // optionals just workletextra:[MyAction] // so does complex types}letaction=MyAction( message:"hi mom", from:"2goodgenes", // most eosio types can be expressed by literals tip:"3.00 BUCKZ", extra:[MyAction(message:"yup", from:"me", tip:nil, extra:[])])// types have same memory layout as their c++ eosio counterpartsprint(action.from.rawValue) // 1380710289163812864print(action.tip!.symbol) // 2,BUCKZprint(action.tip!.units) // 300// types conform to standrad protocols where applicableprint(action.from=="2goodgenes") // trueprint(action.tip!*10) // "30.00 BUCKZ"print(action.tip!+"0.99 BUCKZ") // "3.99 BUCKZ"print(Name(String(action.from).replacingOccurrences(of:"good", with:"BÅÅD"))) // 2....genes// encode action to jsonletjsonEncoder=JSONEncoder()jsonEncoder.outputFormatting=.prettyPrintedletjsonData=try! jsonEncoder.encode(action)print(String(bytes: jsonData, encoding:.utf8)!)/* { "extra" : [ { "message" : "yup", "extra" : [ ], "from" : "me" } ], "message" : "hi mom", "tip" : "3.00 BUCKZ", "from" : "2goodgenes" } */// encode action to binaryletabiEncoder=ABIEncoder()letbinData:Data=try! abiEncoder.encode(action)print(binData.hexEncodedString())// 066869206d6f6d00005653b1442913012c01000000000000024255434b5a0000010379757000000000000080920000// decoding actionsletabiDecoder=ABIDecoder() // same for JSONDecoderletdecodedAction=try! abiDecoder.decode(MyAction.self, from: binData)print(decodedAction== action) // true// untypepd coding using ABI definitionsletmyAbiJson="""{"version":"eosio::abi/1.1","structs": [ {"name":"my_action","base":"","fields": [ {"name":"message","type":"string"}, {"name":"from","type":"name"}, {"name":"tip","type":"asset?"}, {"name":"extra","type":"my_action[]"} ] } ]}"""letjsonDecoder=JSONDecoder()// ABI defs are also ABICodableletabi=try! jsonDecoder.decode(ABI.self, from: myAbiJson.data(using:.utf8)!)print(abi.resolveStruct("my_action")!.map({ $0.name})) // ["message", "from", "tip", "extra"]// untyped decodingletanyFromBin=(try! abiDecoder.decode("my_action", from: binData, using: abi))letanyFromJson=(try! jsonDecoder.decode("my_action", from: jsonData, using: abi))letobjFromBin= anyFromBinas![String:Any]letobjFromJson= anyFromJsonas![String:Any]print(objFromJson["from"]as!Name) // 2goodgenesprint(objFromJson["from"]as?Name==objFromBin["from"]as?Name) // trueprint(objFromJson["from"]as?Name== action.from) // true