SlideShare ist ein Scribd-Unternehmen logo
1 von 24
Downloaden Sie, um offline zu lesen
Introduction to Swift
for Android
Andrew Druk
Spark for Android
Cross-platform native
mobile development
C++ Swift Kotlin Native
Standart library STD + STL Foundation
Korlin Native
Runtime
Memory Manual ARC ARC
Multithreading pthread (for POSIX) GCD Kotlin routines
Build system and
third-party libs
autoconf ->
configure -> make,
CMake, ninja, etc.
Swift package
Manager
Gradle
Objective-C
interoperability
Objective-C++ Just works™ One way
Swift Android Compiler
C Frontend
C++ Frontend
ARM Backend
ARM64 Backend
x86 Backend
x86_64 Backend
C
C++
ARM
ARM64
x86
x86_64
Common
Optimizer
Swift FrontendSwift
LLVM IR LLVM IR
Current compiler limitation
• Only Mac
• Only armv-7a (or with legacy mode on arm64)
• Android 5.0+
• + 32 Mb to apk file
Swift Android Toolchain
git clone https:!//github.com/readdle/swift-android-toolchain
export SWIFT_ANDROID_HOME=$HOME/android/swift-android-4.0d
export PATH=$ANDROID_NDK_HOME:$PATH
export PATH=$SWIFT_ANDROID_HOME/bin:$SWIFT_ANDROID_HOME/build-tools/current:$PATH
wget https:!//dl.bintray.com/readdle/swift-android-toolchain/swift-android-4.0d.zip
swift android tools !--update
OR
PROFILE:
UPDATE ANDROID TOOLS:
Swift Android Toolchain
swift-build
swift package update
swift-test
Build packages:
Test packages:
Update dependencies:
Swift Android Toolchain
!// project.gradle
buildscript {
repositories {
maven { url "https:!//dl.bintray.com/readdle/maven" }
!// …
}2
dependencies {
classpath 'com.readdle.android.swift:gradle:1.1.3'
!// …
}1
}0
!// app.gradle
apply plugin: ‘com.readdle.android.swift'
swift {
cleanEnabled true
debug {
extraBuildFlags("-Xswiftc", "-DDEBUG")
}
}
Java Interoperability
public func swiftFunc(str: String) !-> String?
@_silgen_name("Java_com_readdle_swiftjava_sample_Sample_func")
public func Java_com_readdle_swiftjava_sample_Sample_func(env:
UnsafeMutablePointer<JNIEnv?>,
javaString: jstring) !-> jstring? {
let swiftString: String
do {
swiftString = try String.from(javaObject: this)
}4
catch {
_ = JNI.api.ThrowNew(JNI.env, SwiftRuntimeErrorClass, "Error")
return nil
}3
let result = swiftFunc(str: swiftString)
do {
return try result!?.javaObject()
}2
catch {
_ = JNI.api.ThrowNew(JNI.env, SwiftRuntimeErrorClass, "Error")
return nil
}1
}0
Swift Android Annotation
Processor
@SwiftValue
@SwiftReference
@SwiftDelegate(protocols = {“ProtocolName"})
Java annotations:
Swift Android Annotation
Processor
@SwiftValue
public class SampleValue {
@NonNull
public String str1;
@NonNull
public String str2;
@NonNull
public String str3;
!// Swift JNI constructor
public SampleValue() {
}1
}0
public struct SampleValue: Codable {
public var str1: String
public var str2: String
public var str3: String
}2
Swift Android Annotation
Processor
public class SampleReference {
public func getRandomValue() !-> SampleValue {
return SampleValue(str1: "1", str2: "2", str3: "3")
}3
}2
@SwiftReference
public class SampleReference {
!// Swift JNI private native pointer
private long nativePointer = 0L;
!// Swift JNI private constructor
private SampleReference() {
}1
!// Swift JNI release method
public native void release();
@NonNull
public native SampleValue getRandomValue();
}0
Swift Android Annotation
Processor
public protocol SampleBlockDelegate {
func onCall()
}1
@SwiftDelegate(protocols = {"SampleBlockDelegate"})
public interface SampleInterfaceDelegateAndroid {
@SwiftCallbackFunc
void onCall();
}0
ART (JAVA)
NATIVE (SWIFT)
Blueprint Project
git clone https://github.com/andriydruk/swift-android-architecture
Activity
VIEW
VIEW MODEL
REPOSITORY
(+ in-memory cache)
GENERATED
JNI
XCTest
compile packages
compile tests
copy binaries on Android >>>
run executable
copy resources (optional) >>>
copy results (optional) <<<
Debugging
Debugging
Debugging
Profiling
Profiling
What’s next?
• Swift + Kotlin = ❤
• ARM64 compiler (deadline August 2019)
• X86, X86_64 compiler (Chromebook support)
• LLDB with Swift support: client and server
Sources
• https://github.com/apple/swift/blob/master/docs/Android.md
• https://github.com/SwiftJava/swift-android-kotlin/blob/master/
README.md
• https://modocache.io/how-to-port-the-swift-runtime-to-android
• https://medium.com/@ephemer/why-we-put-an-app-in-the-
android-play-store-using-swift-96ac87c88dfc
• https://romain.goyet.com/articles/
running_swift_code_on_android/
Thank you.
andriy.druk@gmail.com
andriydruk.com
@AndriyDruk

Weitere ähnliche Inhalte

Was ist angesagt?

Clang Analyzer Tool Review
Clang Analyzer Tool ReviewClang Analyzer Tool Review
Clang Analyzer Tool Review
Doug Schuster
 

Was ist angesagt? (20)

Clang Analyzer Tool Review
Clang Analyzer Tool ReviewClang Analyzer Tool Review
Clang Analyzer Tool Review
 
Android Native Development Kit
Android Native Development KitAndroid Native Development Kit
Android Native Development Kit
 
Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!
 
LLVM Compiler - Link Time Optimization
LLVM Compiler - Link Time OptimizationLLVM Compiler - Link Time Optimization
LLVM Compiler - Link Time Optimization
 
Fast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCFast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPC
 
Build Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPCBuild Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPC
 
Refactoring a go project
Refactoring a go projectRefactoring a go project
Refactoring a go project
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate Representation
 
Introduction to the LLVM Compiler System
Introduction to the LLVM  Compiler SystemIntroduction to the LLVM  Compiler System
Introduction to the LLVM Compiler System
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)
 
Lightweight Virtualization with Linux Containers and Docker | YaC 2013
Lightweight Virtualization with Linux Containers and Docker | YaC 2013Lightweight Virtualization with Linux Containers and Docker | YaC 2013
Lightweight Virtualization with Linux Containers and Docker | YaC 2013
 
Android NDK
Android NDKAndroid NDK
Android NDK
 
Native development kit (ndk) introduction
Native development kit (ndk)  introductionNative development kit (ndk)  introduction
Native development kit (ndk) introduction
 
Android ndk
Android ndkAndroid ndk
Android ndk
 
NDK Introduction
NDK IntroductionNDK Introduction
NDK Introduction
 
Safety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Safety on the Max: How to Write Reliable C/C++ Code for Embedded SystemsSafety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Safety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
 
Introduction to the Android NDK
Introduction to the Android NDKIntroduction to the Android NDK
Introduction to the Android NDK
 
A Journey From Objective C to Swift - Chromeinfotech
A Journey From Objective C to Swift - ChromeinfotechA Journey From Objective C to Swift - Chromeinfotech
A Journey From Objective C to Swift - Chromeinfotech
 
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)
 

Ähnlich wie Andrew Druk, Android Developer, Readdie

jhkghj
jhkghjjhkghj
jhkghj
Admin
 
test2PPT
test2PPTtest2PPT
test2PPT
Admin
 
Improving DroidBox
Improving DroidBoxImproving DroidBox
Improving DroidBox
Kelwin Yang
 
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
Sang Don Kim
 
Kandroid for nhn_deview_20131013_v5_final
Kandroid for nhn_deview_20131013_v5_finalKandroid for nhn_deview_20131013_v5_final
Kandroid for nhn_deview_20131013_v5_final
NAVER D2
 

Ähnlich wie Andrew Druk, Android Developer, Readdie (20)

Advance Android Application Development
Advance Android Application DevelopmentAdvance Android Application Development
Advance Android Application Development
 
Android OS Porting: Introduction
Android OS Porting: IntroductionAndroid OS Porting: Introduction
Android OS Porting: Introduction
 
Cross Platform App Development with C++
Cross Platform App Development with C++Cross Platform App Development with C++
Cross Platform App Development with C++
 
Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014
 
Android RenderScript
Android RenderScriptAndroid RenderScript
Android RenderScript
 
Андрей Володин — Как подружиться с роботом
Андрей Володин — Как подружиться с роботомАндрей Володин — Как подружиться с роботом
Андрей Володин — Как подружиться с роботом
 
PIL - A Platform Independent Language
PIL - A Platform Independent LanguagePIL - A Platform Independent Language
PIL - A Platform Independent Language
 
lecture-2-android-dev.pdf
lecture-2-android-dev.pdflecture-2-android-dev.pdf
lecture-2-android-dev.pdf
 
Asp dot net
Asp dot netAsp dot net
Asp dot net
 
iOS for Android Developers (with Swift)
iOS for Android Developers (with Swift)iOS for Android Developers (with Swift)
iOS for Android Developers (with Swift)
 
Android develop guideline
Android develop guidelineAndroid develop guideline
Android develop guideline
 
jhkghj
jhkghjjhkghj
jhkghj
 
test2PPT
test2PPTtest2PPT
test2PPT
 
Asp net
Asp netAsp net
Asp net
 
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
 
Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020
 
Improving DroidBox
Improving DroidBoxImproving DroidBox
Improving DroidBox
 
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
 
Asp net
Asp netAsp net
Asp net
 
Kandroid for nhn_deview_20131013_v5_final
Kandroid for nhn_deview_20131013_v5_finalKandroid for nhn_deview_20131013_v5_final
Kandroid for nhn_deview_20131013_v5_final
 

Mehr von DataArt

Digital Marketing from inside
Digital Marketing from insideDigital Marketing from inside
Digital Marketing from inside
DataArt
 
A. Sirota "Building an Automation Solution based on Appium"
A. Sirota "Building an Automation Solution based on Appium"A. Sirota "Building an Automation Solution based on Appium"
A. Sirota "Building an Automation Solution based on Appium"
DataArt
 
Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...
Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...
Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...
DataArt
 

Mehr von DataArt (20)

DataArt Custom Software Engineering with a Human Approach
DataArt Custom Software Engineering with a Human ApproachDataArt Custom Software Engineering with a Human Approach
DataArt Custom Software Engineering with a Human Approach
 
DataArt Healthcare & Life Sciences
DataArt Healthcare & Life SciencesDataArt Healthcare & Life Sciences
DataArt Healthcare & Life Sciences
 
DataArt Financial Services and Capital Markets
DataArt Financial Services and Capital MarketsDataArt Financial Services and Capital Markets
DataArt Financial Services and Capital Markets
 
About DataArt HR Partners
About DataArt HR PartnersAbout DataArt HR Partners
About DataArt HR Partners
 
Event management в IT
Event management в ITEvent management в IT
Event management в IT
 
Digital Marketing from inside
Digital Marketing from insideDigital Marketing from inside
Digital Marketing from inside
 
What's new in Android, Igor Malytsky ( Google Post I|O Tour)
What's new in Android, Igor Malytsky ( Google Post I|O Tour)What's new in Android, Igor Malytsky ( Google Post I|O Tour)
What's new in Android, Igor Malytsky ( Google Post I|O Tour)
 
DevOps Workshop:Что бывает, когда DevOps приходит на проект
DevOps Workshop:Что бывает, когда DevOps приходит на проектDevOps Workshop:Что бывает, когда DevOps приходит на проект
DevOps Workshop:Что бывает, когда DevOps приходит на проект
 
IT Talk Kharkiv: «‎Soft skills в IT. Польза или вред? Максим Бастион, DataArt
IT Talk Kharkiv: «‎Soft skills в IT. Польза или вред? Максим Бастион, DataArtIT Talk Kharkiv: «‎Soft skills в IT. Польза или вред? Максим Бастион, DataArt
IT Talk Kharkiv: «‎Soft skills в IT. Польза или вред? Максим Бастион, DataArt
 
«Ноль копеек. Спастись от выгорания» — Сергей Чеботарев (Head of Design, Han...
 «Ноль копеек. Спастись от выгорания» — Сергей Чеботарев (Head of Design, Han... «Ноль копеек. Спастись от выгорания» — Сергей Чеботарев (Head of Design, Han...
«Ноль копеек. Спастись от выгорания» — Сергей Чеботарев (Head of Design, Han...
 
Communication in QA's life
Communication in QA's lifeCommunication in QA's life
Communication in QA's life
 
Нельзя просто так взять и договориться, или как мы работали со сложными людьми
Нельзя просто так взять и договориться, или как мы работали со сложными людьмиНельзя просто так взять и договориться, или как мы работали со сложными людьми
Нельзя просто так взять и договориться, или как мы работали со сложными людьми
 
Знакомьтесь, DevOps
Знакомьтесь, DevOpsЗнакомьтесь, DevOps
Знакомьтесь, DevOps
 
DevOps in real life
DevOps in real lifeDevOps in real life
DevOps in real life
 
Codeless: автоматизация тестирования
Codeless: автоматизация тестированияCodeless: автоматизация тестирования
Codeless: автоматизация тестирования
 
Selenoid
SelenoidSelenoid
Selenoid
 
Selenide
SelenideSelenide
Selenide
 
A. Sirota "Building an Automation Solution based on Appium"
A. Sirota "Building an Automation Solution based on Appium"A. Sirota "Building an Automation Solution based on Appium"
A. Sirota "Building an Automation Solution based on Appium"
 
Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...
Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...
Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...
 
IT talk: Как я перестал бояться и полюбил TestNG
IT talk: Как я перестал бояться и полюбил TestNGIT talk: Как я перестал бояться и полюбил TestNG
IT talk: Как я перестал бояться и полюбил TestNG
 

Kürzlich hochgeladen

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Krashi Coaching
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Kürzlich hochgeladen (20)

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 

Andrew Druk, Android Developer, Readdie

  • 1. Introduction to Swift for Android Andrew Druk
  • 2.
  • 4. Cross-platform native mobile development C++ Swift Kotlin Native Standart library STD + STL Foundation Korlin Native Runtime Memory Manual ARC ARC Multithreading pthread (for POSIX) GCD Kotlin routines Build system and third-party libs autoconf -> configure -> make, CMake, ninja, etc. Swift package Manager Gradle Objective-C interoperability Objective-C++ Just works™ One way
  • 5. Swift Android Compiler C Frontend C++ Frontend ARM Backend ARM64 Backend x86 Backend x86_64 Backend C C++ ARM ARM64 x86 x86_64 Common Optimizer Swift FrontendSwift LLVM IR LLVM IR
  • 6. Current compiler limitation • Only Mac • Only armv-7a (or with legacy mode on arm64) • Android 5.0+ • + 32 Mb to apk file
  • 7. Swift Android Toolchain git clone https:!//github.com/readdle/swift-android-toolchain export SWIFT_ANDROID_HOME=$HOME/android/swift-android-4.0d export PATH=$ANDROID_NDK_HOME:$PATH export PATH=$SWIFT_ANDROID_HOME/bin:$SWIFT_ANDROID_HOME/build-tools/current:$PATH wget https:!//dl.bintray.com/readdle/swift-android-toolchain/swift-android-4.0d.zip swift android tools !--update OR PROFILE: UPDATE ANDROID TOOLS:
  • 8. Swift Android Toolchain swift-build swift package update swift-test Build packages: Test packages: Update dependencies:
  • 9. Swift Android Toolchain !// project.gradle buildscript { repositories { maven { url "https:!//dl.bintray.com/readdle/maven" } !// … }2 dependencies { classpath 'com.readdle.android.swift:gradle:1.1.3' !// … }1 }0 !// app.gradle apply plugin: ‘com.readdle.android.swift' swift { cleanEnabled true debug { extraBuildFlags("-Xswiftc", "-DDEBUG") } }
  • 10. Java Interoperability public func swiftFunc(str: String) !-> String? @_silgen_name("Java_com_readdle_swiftjava_sample_Sample_func") public func Java_com_readdle_swiftjava_sample_Sample_func(env: UnsafeMutablePointer<JNIEnv?>, javaString: jstring) !-> jstring? { let swiftString: String do { swiftString = try String.from(javaObject: this) }4 catch { _ = JNI.api.ThrowNew(JNI.env, SwiftRuntimeErrorClass, "Error") return nil }3 let result = swiftFunc(str: swiftString) do { return try result!?.javaObject() }2 catch { _ = JNI.api.ThrowNew(JNI.env, SwiftRuntimeErrorClass, "Error") return nil }1 }0
  • 12. Swift Android Annotation Processor @SwiftValue public class SampleValue { @NonNull public String str1; @NonNull public String str2; @NonNull public String str3; !// Swift JNI constructor public SampleValue() { }1 }0 public struct SampleValue: Codable { public var str1: String public var str2: String public var str3: String }2
  • 13. Swift Android Annotation Processor public class SampleReference { public func getRandomValue() !-> SampleValue { return SampleValue(str1: "1", str2: "2", str3: "3") }3 }2 @SwiftReference public class SampleReference { !// Swift JNI private native pointer private long nativePointer = 0L; !// Swift JNI private constructor private SampleReference() { }1 !// Swift JNI release method public native void release(); @NonNull public native SampleValue getRandomValue(); }0
  • 14. Swift Android Annotation Processor public protocol SampleBlockDelegate { func onCall() }1 @SwiftDelegate(protocols = {"SampleBlockDelegate"}) public interface SampleInterfaceDelegateAndroid { @SwiftCallbackFunc void onCall(); }0
  • 15. ART (JAVA) NATIVE (SWIFT) Blueprint Project git clone https://github.com/andriydruk/swift-android-architecture Activity VIEW VIEW MODEL REPOSITORY (+ in-memory cache) GENERATED JNI
  • 16. XCTest compile packages compile tests copy binaries on Android >>> run executable copy resources (optional) >>> copy results (optional) <<<
  • 22. What’s next? • Swift + Kotlin = ❤ • ARM64 compiler (deadline August 2019) • X86, X86_64 compiler (Chromebook support) • LLDB with Swift support: client and server
  • 23. Sources • https://github.com/apple/swift/blob/master/docs/Android.md • https://github.com/SwiftJava/swift-android-kotlin/blob/master/ README.md • https://modocache.io/how-to-port-the-swift-runtime-to-android • https://medium.com/@ephemer/why-we-put-an-app-in-the- android-play-store-using-swift-96ac87c88dfc • https://romain.goyet.com/articles/ running_swift_code_on_android/