语言比较

Hello World

//OC
NSLog(@"Hello, world!");

//Swift
print("Hello, world!")

//JAVA
System.out.println("Hello, world!");

//Kotlin
println("Hello, world!")

Variables And Constants

//OC
NSInteger myVariable = 42;
myVariable = 50;
NSInteger const myConstant = 42;

//Swift
var myVariable = 42
myVariable = 50
let myConstant = 42

//JAVA

int myVariable = 42;
myVariable = 50;
final int myConstant = 42;

//Kotlin
var myVariable = 42
myVariable = 50
val myConstant = 42

Explicit Types

//OC
CGFloat explicitDouble = 70;

//Swift
var explicitDouble: Double = 70


//JAVA
double explicitDouble = 70.0;

//Kotlin
var explicitDouble: Double = 70.0

Type Coercion

//OC
NSString *label = @"The width is ";
CGFloat width = 94;
NSString *widthLabel = [NSString stringWithFormat:@"%@%g",label,width];

//Swift
let label = "The width is "
let width = 94
let widthLabel = label + String(width)

//JAVA
final String label = "The width is ";
final double width = 94;
final String widthLabel = label + width;

//Kotlin
val label = "The width is "
val width = 94
val widthLabel = label + width

String Interpolation

//OC
NSInteger apples = 3;
NSInteger oranges = 5;
NSString *fruitSummary = [NSString stringWithFormat:@"I have %ld pieces of fruit.",apples + oranges];

//Swift
let apples = 3
let oranges = 5
let fruitSummary = "I have \(apples + oranges) " +
                   "pieces of fruit."

//JAVA
final int apples = 3;
final int oranges = 5;
final String fruitSummary = "I have "+ (apples + oranges) +"  pieces of fruit.";

//Kotlin
val apples = 3
val oranges = 5
val fruitSummary = "I have ${apples + oranges} " +
                   "pieces of fruit."

Range Operator

//OC
NSArray *names = @[@"Anna",@"Alex",@"Brian",@"Jack"];
for (int i = 0; i < names.count; i++) {
    NSLog(@"Person %d is called %@",i,names[i]);
}
//Swift
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
    print("Person \(i + 1) is called \(names[i])")
}

//JAVA
ArrayList<String> names = new ArrayList();
names.add("Anna");
names.add("Alex");
names.add("Brian");
names.add("Jack");
for(int i = 0; i < names.size(); i++){
    System.out.println("Person "+ i + 1 +" is called " + names.get(i) );
}

//Kotlin
val names = arrayOf("Anna", "Alex", "Brian", "Jack")
val count = names.count()
for (i in 0..count - 1) {
    println("Person ${i + 1} is called ${names[i]}")
}

Inclusive Range Operator

//OC
for (int index = 1; index <= 5; index++) {
   NSLog(@"%d times 5 is %d",index,index * 5);
}

//Swift
//a...b   [a,b] 整数
//a..<b   [a,b) 整数
for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}

//JAVA
for(int i = 1; i <= 5; i++){
    System.out.println(i + "times 5 is" + i * 5);
}

//Kotlin
for (index in 1..5) {
    println("$index times 5 is ${index * 5}")
}

Arrays

//OC
NSMutableArray *shoppingList = [NSMutableArray arrayWithArray:@[@"catfish", @"water", @"tulips", @"blue paint"]];
shoppingList[1] = @"bottle of water";

//Swift
var shoppingList = ["catfish", "water",
    "tulips", "blue paint"]
shoppingList[1] = "bottle of water"

//JAVA
ArrayList<String> shoppingList = new ArrayList();
names.add("catfish");
names.add("water");
names.add("tulips");
names.add("blue paint");
shoppingList.set(1,"bottle of water");

//Kotlin
val shoppingList = arrayOf("catfish", "water",
    "tulips", "blue paint")
shoppingList[1] = "bottle of water"

Maps

//OC
NSMutableDictionary *occupations = [NSMutableDictionary dictionaryWithDictionary:@{@"Malcolm":@"Captain",@"Kaylee":@"Mechanic"}];
occupations[@"Jayne"] = @"Public Relations";

//Swift
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

//JAVA
HashMap occupations = new HashMap();
occupations.put("Malcolm", "Captain");
occupations.put("Kaylee", "Mechanic");
occupations.put("Jayne","Public Relations");

//Kotlin
val occupations = mutableMapOf(
    "Malcolm" to "Captain",
    "Kaylee" to "Mechanic"
)
occupations["Jayne"] = "Public Relations"

Empty Collections

//OC
NSArray *emptyArray = [NSArray array];
NSDictionary *emptyDictionary = [NSDictionary dictionary];

//Swift
let emptyArray = [String]()
let emptyDictionary = [String: Float]()

//JAVA
ArrayList<String> emptyArray = new ArrayList();
HashMap<String,Float> emptyMap = new HashMap();

//Kotlin
val emptyArray = arrayOf<String>()
val emptyMap = mapOf<String, Float>()

Functions

//OC
-(NSString *)greetWithName:(NSString *)name andDay:(NSString *)day{
    return [NSString stringWithFormat:@"Hello %@, today is %@.",name,day];
}
[self greetWithName:@"Bob" andDay:@"Tuesday"];

//Swift
func greet(_ name: String,_ day: String) -> String {
    return "Hello \(name), today is \(day)."
}
greet("Bob", "Tuesday")

//JAVA
private String greet(String name, String day){
    return "Hello " + name + "today is " + day + ".";
}
greet("Bob", "Tuesday");

//Kotlin
fun greet(name: String, day: String): String {
    return "Hello $name, today is $day."
}
greet("Bob", "Tuesday")

Tuple Return

//OC
//并没有元组这个东西哦~

//Swift
func getGasPrices() -> (Double, Double, Double) {
    return (3.59, 3.69, 3.79)
}

//JAVA
//非语言自身支持

//Kotlin
data class GasPrices(val a: Double, val b: Double,
     val c: Double)
fun getGasPrices() = GasPrices(3.59, 3.69, 3.79)

Variable Number Of Arguments

//OC
-(NSInteger)sumOf:(NSNumber *)numbers , ...{
    NSInteger sum = 0;
    if (numbers) {
        sum += [numbers integerValue];
        va_list args;
        NSString *arg;
        va_start(args, numbers);
        while ((arg = va_arg(args, NSString *))) {
            sum += [arg integerValue];
        }
        va_end(args);
    }
    return sum;
}
[self sumOf:@42, @597, @12];

//Swift
func sumOf(_ numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
sumOf(42, 597, 12)

//JAVA
private int sumOf( int... numbers) {
    int sum = 0;
    for (int number : numbers ){
        sum += number;
    }
    return sum;
}
sumOf(42, 597, 12);

//Kotlin
fun sumOf(vararg numbers: Int): Int {
    var sum = 0
    for (number in numbers) {
        sum += number
    }
    return sum
}
sumOf(42, 597, 12)

Function Type

//OC
-(int(^)(int))increment
{
    return ^int(int number){
        return number + 1;
    };
}
[self increment](7);

//Swift
func makeIncrementer() -> (Int -> Int) {
    func addOne(number: Int) -> Int {
        return 1 + number
    }
    return addOne
}
let increment = makeIncrementer()
increment(7)

//JAVA
private Active makeIncrementer()
{
    return new Active() {
        @Override
        public int addOne(int number) {
            return number + 1;
        }
    };
}
makeIncrementer().addOne(7);
interface Active
{
    int addOne(int number);
}

//Kotlin
fun makeIncrementer(): (Int) -> Int {
    val addOne = fun(number: Int): Int {
        return 1 + number
    }
    return addOne
}
val increment = makeIncrementer()
increment(7)

Sort

//OC
NSArray *mutableArray = @[@1, @5, @3, @12, @2];
mutableArray = [mutableArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
     return [obj1 integerValue] < [obj2 integerValue] ? NSOrderedAscending : NSOrderedDescending;
}];

//Swift
var mutableArray = [1, 5, 3, 12, 2]
mutableArray.sort()

//JAVA
ArrayList<Integer> mutableArray = new ArrayList();
mutableArray.add(1);
mutableArray.add(5);
mutableArray.add(3);
mutableArray.add(12);
mutableArray.add(2);
Collections.sort(mutableArray);

//Kotlin
listOf(1, 5, 3, 12, 2).sorted()

Named Arguments

//OC
-(NSInteger)areaWithWidth:(NSInteger)width height:(NSInteger)height{
    return width * height;
}
[self areaWithWidth:2 height:3];

//Swift
func area(width: Int, height: Int) -> Int {
    return width * height
}
area(width: 2, height: 3)

//JAVA
private int area(int width,int height){
    return width * height;
}
area(2,3);

//Kotlin
fun area(width: Int, height: Int) = width * height
area(width = 2, height = 3)
area(2, height = 2)
area(height = 3, width = 2)

Declaration

//OC
//注: 这里的Shape一般会被命名为XXShape或XXXShape
@interface Shape : NSObject

@property (nonatomic,assign)NSInteger numberOfSides;

-(NSString *)simpleDescription;

@end

@implementation Shape

-(NSString *)simpleDescription{

    return [NSString stringWithFormat:@"A shape with %ld sides.",self.numberOfSides];
}
@end

Shape *shape = [[Shape alloc]init];
shape.numberOfSides = 7;
NSString *shapeDescription = [shape simpleDescription];

//Swift
class Shape {
    var numberOfSides = 0
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

//JAVA
public class Shape {
    int numberOfSides;
    public String simpleDescription(){
        return "A shape with %ld sides." + numberOfSides;
    }
}

Shape shape = new Shape();
shape.numberOfSides = 7;
String shapeDescription = shape.simpleDescription();

//Kotlin
class Shape {
    var numberOfSides = 0
    fun simpleDescription() = "A shape with $numberOfSides sides."
}

var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

Subclass

//OC
@interface NamedShape : NSObject

@property (nonatomic,assign)NSInteger numberOfSides;

@property (nonatomic,copy)NSString *name;

- (instancetype)initWithName:(NSString *)name;

-(NSString *)simpleDescription;

@end

@implementation NamedShape

- (instancetype)initWithName:(NSString *)name
{
    self = [super init];
    if (self) {

        self.name = name;

    }
    return self;
}

-(NSString *)simpleDescription{

    return [NSString stringWithFormat:@"A shape with %ld sides.",self.numberOfSides];

}

@end

@interface Square : NamedShape

@property (nonatomic,assign)CGFloat sideLength;

- (instancetype)initWithSideLength:(CGFloat)sideLength andName:(NSString *)name;

- (CGFloat)area;

@end

@implementation Square

- (instancetype)initWithSideLength:(CGFloat)sideLength andName:(NSString *)name
{
    self = [super initWithName:name];
    if (self) {
        self.sideLength = sideLength;
        self.numberOfSides = 4;
    }
    return self;
}

- (CGFloat)area{
    return self.sideLength * self.sideLength;
}

- (NSString *)simpleDescription{
    return [NSString stringWithFormat:@"A square with sides of length %lf.", self.sideLength];
}

@end

Square *test = [[Square alloc]initWithSideLength:5.2 andName:@"square"];
test.area;
[test simpleDescription];

//Swift
class NamedShape {
    var numberOfSides: Int = 0
    let name: String

    init(name: String) {
        self.name = name
    }

    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

class Square: NamedShape {
    var sideLength: Double

    init(sideLength: Double, name: String) {
        self.sideLength = sideLength
        super.init(name: name)
        self.numberOfSides = 4
    }

    func area() -> Double {
        return sideLength * sideLength
    }

    override func simpleDescription() -> String {
        return "A square with sides of length " +
           sideLength + "."
    }
}

let test = Square(sideLength: 5.2, name: "square")
test.area()
test.simpleDescription()

//JAVA
public class NamedShape {

    int numberOfSides = 0;

    String name;

    public NamedShape() {
    }

    public NamedShape(String name){
        this.name = name;
    }
    public String simpleDescription(){
        return "A shape with " + numberOfSides + " sides.";
    }

}

public class Shape {

    int numberOfSides;

    public String simpleDescription(){
        return "A shape with %ld sides." + numberOfSides;
    }

}

Square test = new Square(5.2,"square");
test.area();
test.simpleDescription();

//Kotlin
open class NamedShape(val name: String) {
    var numberOfSides = 0

    open fun simpleDescription() =
        "A shape with $numberOfSides sides."
}

class Square(var sideLength: BigDecimal, name: String) :
        NamedShape(name) {
    init {
        numberOfSides = 4
    }

    fun area() = sideLength.pow(2)

    override fun simpleDescription() =
        "A square with sides of length $sideLength."
}

val test = Square(BigDecimal("5.2"), "square")
test.area()
test.simpleDescription()

Checking Type

//OC
NSArray *library = @[[[Movie alloc]init],[[Song alloc]init]];
for (Library *item in library) {
    if ([item isKindOfClass:[Movie class]]) {
       NSLog(@"Movie");
    }else if ([item isKindOfClass:[Song class]]) {
       NSLog(@"Song");
    }
}

//Swift
let library = [Movie(),Song()]
for item in library {
    if item is Movie {
        print("Movie")
    } else if item is Song {
        print("Song")
    }
}

//JAVA
ArrayList<Library> library = new ArrayList();
library.add(new Song());
library.add(new Movie());
for (Library item : library) {
    if (item instanceof Movie){
        System.out.println("Movie");
    }else if(item instanceof Song){
        System.out.println("Song");
    }
}

//Kotlin
val library = arrayOf(Movie(),Song())
for (item in library) {
    if (item is Movie) {
        print("Movie")
    } else if (item is Song) {
        print("Song")
    }
}

Protocol

//OC
@protocol Nameable
-(NSString *)name;
@end

//Swift
protocol Nameable {
    func name() -> String
}


//JAVA
interface Nameable {
    fun name(): String
}

//Kotlin
interface Nameable {
    fun name(): String
}

Extensions

//OC
//Category
@interface NSString (Add)

-(NSString *)add:(NSString *)string;

@end

@implementation NSString (Add)

-(NSString *)add:(NSString *)string{
    return [NSString stringWithFormat:@"%@+%@",self,string];
}

@end

    NSString *string = [@"A" add:@"B"];

//Swift
extension Double {
    var km: Double { return self * 1000.0 }
    var m: Double { return self }
    var cm: Double { return self / 100.0 }
    var mm: Double { return self / 1000.0 }
    var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm

//JAVA
//无此功能

//Kotlin
val Double.km: Double get() = this * 1000
val Double.m: Double get() = this
val Double.cm: Double get() = this / 100
val Double.mm: Double get() = this / 1000
val Double.ft: Double get() = this / 3.28084

val oneInch = 25.4.mm
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值