Kotlin is the latest development language for Android;
Swift is the latest development language for iOS;
The two grammars are similar, so compare them below.
Kotlin Chinese Website: https://www.kotlincn.net/docs/reference/basic-syntax.html
By Official Document order:
Function
Kotlin
Swift
Description
Defining packages
Package Com.*.* Example: Pacakge com.brycegao.test
Import * Instance: Import Uikit
1, the Kotlin declaration definition package is the same as Java, package name must be lowercase letters, 2, Swift refers to the library using the Import keyword.
Reference class
Import *.*.* instance: Import java.util.*
Just reference the Library
Kotlin is the same as Java, Swift does not need to reference the class, only need to reference the library;
Defining functions
Fun sum (A:int, b:int): Int {
Return a + b
If the function body has only one line of code, you can abbreviate the function. Fun sum (A:int, b:int): Int = a + b calling method: Sum (1, 2)
Func sum (Label1 a:int, Label2 b:int)->int {return a + B} Call mode: Sum (lable1:1, Label2:2)
1, Kotlin uses fun as the function key word, 2, Func uses the Func as the function key word; 3, Kotlin use: Separating parameters and return value types; 4, Swift uses-> to delimit parameters and return value types;
Variable parameters
var keyword example: var a:int = 1
var keyword example: var a:int = 1 var b:int//Can not assign value
Both Kotlin and Swift declare mutable parameters with the var keyword, and parameter values can be modified and declared without assigning values.
Constant parameters
The Val keyword example: val a:int = 1
Let key word example: let A:int = 1
You must assign a value when you declare it, and the parameter value cannot be changed
Comments
One-line comment//Multiline Comment * *
One-line comment//Multiline Comment * *
Swift and Kotlin annotation methods are the same
String templates
var a = 1 var s1 = "A is $a"//enclosed in double quotes $ followed by Parameter A = 2 val s2 = "${s1.replace" (" Is ", ' was ')}, but now is $a"
var a = 1
var S1 = "A is \" (a)
A = 2
Let S2 = "\ (s1.replacingoccurrences (of: ' Is ', with: ' is '), but ' Now ' \ (a)"
1. Kotlin uses $ and {} to declare parameters or call functions; 2, Swift uses \ () to contain parameters;
Escape
val s = "My name is \ \ zhangsan\"
Let S = "I name is \ \ zhangsan\"
Using the \ Escape
An IF condition expression
Fun Maxof (A:int, B:int): Int {
if (a > B) {
Return a
} else {
Return b
}
or fun Maxof (A:int, b:int): Int = if (a > B) a else B
Func Maxof (Label1 a:int, Label2 b:int)->int {
If a > B {
Return a
} else {
Return b
}
}
If condition is true then enter the function body, for false access to else function body
Empty
Null
Nil
Nullable value parameter
Add a question mark after the Type keyword, such as Var a:int? = NULL
var a:int? = Nil
Use a question mark to indicate that the parameter may be empty
Array
Val arr1 = Listof ("Apple", "banana", "Kiwi")
Val arr2 = bytearrayof (1, 2, 3, 4)
Val arr3 = Intarray (5)
Val arr4 = Floatarray (5)
Val arr5 = Doublearray (5)
Val arr6 = Booleanarray (5)
Let Array1 =[1, 2, 3, 4, 5]//int type array
Let array2:array<int> = Array ()//Declaration and definition of INT arrays
Let Array3:[int] =[]//Declare and instantiate an INT array
Let Array4 = Array (repeating:0, count:5)//array has 5 values, all 0
1, the Kotlin must use function to define the array, 2, Swift defines the array more versatile and flexible;
Traversing an array
For (item in arr1) {
println (item)
}
Or
For (i in arr1.indices) {
println (Arr1[i])//by subscript value
}
For item in Array1 {
Print (item)
}
Or
var i = 0
While I < Array1.count {
Print (Array1[i])
i + 1
}
1, all support for-in cycle, 2, through the subscript traversal;
Interval operator
.. is the interval operator, which is equivalent to [] for example: For (i in 1..5) {
Print (i)//output 1,2,3,4,5
for (i in1. Ten Step 2) {
Print (i)//output 1,3,5,7,9
}
... is the interval operator, which is equivalent to []; .. < equivalent to [) for I in 1...5 {
Print (i)//output 1,2,3,4,5
}
For I in 1..<5 {
Print (i)//output 1,2,3,4
}
Kotlin supports setting step steps, Swift step size can only be 1.
Statement separator
Using semicolons, the default does not write var O1 = 1; A line can only write a single statement
var O2 = 2
var O1 = 1;
var O2 = 2
are separated by semicolons and are not written by default
Null return value
Unit//return value is NULL
Fun method (): unit {
}
Fun Method1 () {
}
void Func method ()-> void {
}
Or
Func method1 () {
}
The function return value is NULL, you can omit the return value type, or use the unit, void keyword
Class
Inheritance is not supported by default, equivalent to final class in Java
Class SomeClass {
}
Use the Open keyword to represent a class that can be inherited
Open Class Basicclass Constructor (name:string) {
var value:string
init {
Value = name//Primary constructor
}//Sub-structure A constructor must call the primary constructor
Constructor (Age:int, name:string): This (name) {
function body
}
//... Property methods
}
Class Ext:basicclass ("Basic") {
//... Properties, Methods
}
Class Basicclass {
var name:string?
var age:int?
Init (param:string?) {//constructor
name = param
Print ("Call constructor 1 \ (name)")
}
Convenience init (age param1:int, name param2:string) {
Self.init (PARAM:PARAM2)
Age = param1
}
//... Properties and Functions
Deinit {
destructor
}
}
Let obj1 = Basicclass (age:10, Name: "Zhangsan")//derived class
Class Ext:basicclass {
//... Properties and Functions
}
1, the Kotlin class does not support inheritance by default, you must use the Open keyword to represent inheritable, 2, swift defaults to support inheritance, 3, Kotlin use Contructor to define constructs function, which is divided into primary and secondary constructors, the secondary constructor must call the primary constructor, 4, Kotlin uses this to invoke other constructors, 5, Swift uses this to invoke other constructors, but you must add the convenience keyword 6. Swift uses Init as a constructor and Deinit as a destructor;
Structural body
does not support
struct keyword value type
The difference between swift classes and structs is reference type, value type
Self-increasing or self-reduction
VARA1 = 1
Print (a1++)//Output 1
Print (++A1)//Output 3
Print (a1--)//Delete 3
Print (--A1)//Output 1
var a = 1
A + + 1
A-= 1
1, Kotlin support + + and-; 2. Swift does not support + + and-, but it supports + + and-+.
Control flow
var x = 10
When (x) {//No break keyword
0, 1-> {//comma delimited, when x equals 0 or 1 o'clock execution
Print ("first statement")
Print ("second statement")
}
2-> {//only 1 values
Print ("value equals 2")
}
In 3..10-> {//Interval operators, keywords are in and. Value is [3,10]
Print ("Interval operator")
}
!in 11..20-> {//value is not in [11,20] range
else-> {
Conditions are not met, default processing
}
}
var a = switch a {
Case 0, 1://Multiple conditions
Print ("first statement")
Print ("second statement")
Case 2://A condition
Print ("value equals 2")
Case 3...10://Interval operator
Print ("Interval operator")
Case 10...1000 where a%10==0://Add where condition to judge condition
Print ("Execute where statement")
Default
Print ("Default processing")
}
1, Kotlin use when as a condition to judge the keyword, do not break the keyword; 2, Swift uses the Switch keyword as a branch to judge the keyword;
If
Vara = 1
var B = 2
Val max = if (a>b) {
Print ("Choose a")
A
} else {
Print ("Choose b")
B
}
var a = 1
var B = 2
var max:int
If a > B {
max = a
} else {
max = b
}
Kotlin and Swift have the same logic as the IF statement, the difference being that the swift if statement does not require parentheses
Non-null operator
VALS1 = "This is a string"
Val s2:string? =null
Val ret1 = S1?: Return
Val Ret2 = S1?: "Default Value"
Val ret3 = s2?: "Default Value"
Val ret4 = S1?: "Default"
Print (RET1)//this is a string
Print (Ret2)//default value
Print (RET3)//default value
Print (RET4)//this is a string
Kotlin use?: As an operator, if the front value is non-null, equal to the previous, or the following value
Let S1 = ' This is a string '
Let s2:string? = Nil
Let Ret1 = S1?? ' Default '//this is a string
Let Ret2 = s2?? "Default"//default
1, Kotlin use?: As an operator to take a non-null value, 2, Swift use?? Take a non-null value as an operator;
Label
The identifier is followed by @, where the code jumps, and the syntax is similar to the C-language Goto. loop@ for (i in 1..100) {
For (j in 1..100) {
if (...) break@loop
}
}
does not support
1, Kotlin use of the branch jump syntax, 2, has long been eliminated the syntax, the impact of the overall code logic, not recommended.
Interface
interface keyword
Protocol keyword
Do not implement the function body
Inner class
Inner keyword that holds a reference when an inner class accesses an external class. Example: Super@outer
Open Class Foo {
Open Fun F () {println ("foo.f ()")}
Open Val X:int get () = 1/read-only property
}
Class Bar:foo () {
Override Fun F () {/* ... */}
Override Val X:int get () = 0
Inner class Baz {
Fun g () {
SUPER@BAR.F ()//Call Foo implementation F ()
println (super@bar.x)//getter for X implemented with Foo
}
}
}
Class Ext:basic {
Override Func method () {
Print ("Ext class method")
}
Inner class cannot access external class
Class Baz {
Func g () {
}
}
}
1. Kotlin internal classes hold references to external classes, but there are differences in syntax. 2, Kotlin support coverage methods and properties; 3, Swift supports overlay methods, does not support overwriting properties, 4, Swift internal class cannot access external Class methods, attributes, 5, all use the Override keyword coverage method;
Single case
The
Kotlin does not support static types and uses companion objects. Use a private constructor and add a sync lock, class cannot be inherited; &N Bsp class Singl ETon Private Constructor (str:string) {
var name:string? =null
var age:int =0
&nb Sp var addr:string = "Address"
init {
println ("The STR is $str")
name = str
}
Companion object {
&NB Sp @Volatile
private var Instance:singleton? =null
&NBSP ; Fun getinstance (c:string): SingleTon {
if (instance ==null) {
&N Bsp