Java and Swift comparison (1) Source control / Scope / Variables

Introduction

I want to do something like this, mainly from the perspective of a Java engineer (Java or Swift), can't I do this? It will be the tips to use at that time.

Java 8 was announced and Kotlin was officially adopted in Android Studio 3.0, but when an engineer who was only doing Java develops iOS apps with Xcode, or an engineer who was developing iOS apps with Swift is Java I hope it helps if you want to check at the language notation level when trying to develop Android.

This page mainly deals with Java / Swift notation of "source control", "scope", and "variable". This article is based on 1.7 for Java and Swift3 for Swift, but I'm sorry if there is a notation mistake.

--Comparison between Java and Swift (1) Source control / Scope / Variables -Comparison between Java and Swift (2) Basic type / Arithmetic expression / Control syntax / Function definition -Comparison between Java and Swift (3) Class implementation / Class inheritance / Class design

Source control

Java It is managed by packages, and packages are (generally) determined on a per-directory hierarchy. Even classes in the same project can be treated and created as separate classes in Test.class in the aaa.bbb.ccc package and Test.class in the aaa.bbb.xxx package.

However, if you want to use different package classes in the same project, you need to declare "import import target" at the beginning of the source file or access it with the full qualifier. However, the java.lang package contains frequently used classes, and the classes contained in them (String, Integer, etc.) can be used without being explicitly imported.

python


import java.util.List;
import java.util.ArrayList;

public class Main {
	public static void main(String[] args) {
		List<String> list = new ArrayList();
		java.util.Map<String, String> list = new java.util.HashMap<>();
	}
}

source file

The source file must have a "* .java" extension. Also, the Java source file can only contain one public class, and the Java source file name and the public class name must match.

Swift In Swift, the package is determined for each module (project), and the module name is determined as the namespace. Therefore, if you are in the same module, you can access it only by the class name regardless of the directory hierarchy or source, but you need to be careful about class name conflicts. At this time, when using a class of another module (for example, a library project), it is necessary to declare "import import target package" at the beginning of the source file or access with a full qualifier such as "target package.class name". there is.

python


import Foundation

class Main {
    var arr:Array = Array<String>()
    var date:Foundation.Date = Foundation.Date()
}

source file

The source file must have a "* .swift" extension. Also, unlike Java, Swift source files can be given any file name. In addition, multiple classes can be defined for one file name regardless of the scope.

scope

Java In Java, access control is basically determined for each package and class.

Access modifier Description
public Accessable from all classes and packages
protected Accessable within the same package and from subclasses
(No qualifier) Can be accessed from within the same package
private Only accessible from within the same class

Swift In Swift, access control is basically decided for each module and file.

Access modifier Description
open All classes, accessible from different modules(Swift3 or later)
public All classes, accessible from different modules, not Overide
internal Accessable from within the same module
(No qualifier) Same access control as "internal"
fileprivate Can be accessed from within the same file(Swift3 or later)
private Only accessible from within the same file

variable

First, both are statically typed languages. The type is determined before compile time, and it is obvious that Java etc. are explicitly specified at the time of variable declaration, but even in the case of notation such as "var hoge1 = hoge2" at the time of variable declaration like Swift. , The type of a variable is determined by type inference at the time it is declared.

Java

Variable declaration method

Specify "Type name Variable name = Initial value;".

python


String hoge = "";

The initial value is not required at the time of declaration, and it is possible to declare "type name variable name;", but if the value is not set when actually accessing the variable, a compile error will occur. Also, if the value is indefinite, you can specify null, but if you try to access a variable that is null, you will get a NullpointerException exception.

Constant declaration method

Specify "final type name variable name = initial value;". As with Swift's constant declaration, you cannot reset the value after setting the initial value.

python


final String hoge = "";

Note that Java is a completely object-oriented language, so variables and constants are always associated with a class or instance, and variables and constants cannot be defined outside the class. At this time, when defining a constant associated with a class, declare it as a static final (constant), call this a class constant, and specify "static final type name variable name = initial value;" .. Class constants are defined by Java naming conventions that are declared in uppercase alphanumeric characters.

Swift

Variable declaration method

Specify "var variable name: type name = initial value". In addition, Swift has a language specification called Optional Type, and you cannot set nil for variables that are non-Optional type.

python


var hoge:String = ""

What is Optional Type?

Corresponds to Java8 Optional type and Kotlin Optional. Optional Type is a variable that can hold the nil state in addition to the normal value of the variable type. The initial value of Optional Type is set to nil. In Swift, unlike Java, variables that are not Optional Type are guaranteed not to be nil (null) at the notation level. Optional Type has an explicit specification and a specification to automatically unwrap when a variable is used.

Explicit Optional Type

Specify "?" After the type name, such as "var variable name: type name? = Initial value".

python


var hoge:String? = ""

If you specify an explicit Optional Type, the variable cannot be used in the same way as the original type and must be unwrapped when used. If you try to manipulate an explicit Optional Type without unwrapping it, you will get a compile error.

python


var hoge:String? = "ABC" //Declare a variable with an explicit Optional Type
print(hoge.lowercased()) //Compile error
Optional Type Unwrap

Unwrapping an Optional Type means making an Optional Type variable available in the same way as the original type. There are several ways to unwrap, some should be used when there is no possibility of nil programmatically, and some should be used when there is a possibility of nil programmatically.

If there is no possibility of nil

After specifying "!" After the type name, such as "variable name !. operation", describe the operation such as property and method.

python


var hoge:String? = "ABC" //Declare a variable with an explicit Optional Type
print(hoge!.lowercased()) //"Abc" is output

However, if the variable you are trying to unwrap is nil, you will get a runtime error at run time.

python


hoge = nil //Optional Type can be set to nil
print(hoge!.lowercased()) //Run-time error occurs

Therefore, it is effective when writing the following programs.

python


var hoge:String?
if Date().timeIntervalSince1970 > 0 {
    hoge = "abc"
} else {
    hoge = "cde"
}
print(hoge!.lowercased())
If there is a possibility of nil

After specifying "?" After the type name, such as "variable name ?. operation", describe the operation such as property and method. Unlike the case of forcibly unwrapping with "Variable name !. Operation", nil is returned.

python


var hoge:String? = nil //Optional Type can be set to nil
print(hoge?.lowercased()) //No runtime error, nil is output

Implicit Optional Type

Specify "!" After the type name, such as "var variable name: type name! = Initial value".

python


var hoge:String! = ""

If you specify an implicit Optional Type, you don't have to explicitly unwrap it in your code when using a variable, it will be automatically unwrapped when you use it.

python


var hoge:String! = "ABC" //Declare a variable with an implicit Optional Type
print(hoge.lowercased()) //Can be used without explicitly unwrapping. "Abc" is output

Therefore, when using a variable, you can basically use the original type without considering that it is nil, but if you try to operate a variable of Optional Type with nil set, the runtime An error will occur.

python


var hoge:String! = "ABC" //Declare a variable with an implicit Optional Type
hoge = nil //Optional Type can be set to nil
print(hoge.lowercased()) //Run-time error occurs

In the case of implicit Optional Type, it is necessary to implement it so that it is guaranteed that it is not nil enough when using the variable sufficiently.

Constant declaration method

Specify "let variable name: type name = initial value;". As with Java constant declarations, you cannot reset the value after setting the initial value.

python


let hoge:String = ""

Note that unlike Java, Swift is not an object-oriented language (Swift is a protocol-oriented language), so it is not always necessary to associate it with a class or instance, and you can define constants directly in the file. I can do it. Constants defined directly in the file are guaranteed to be virtually statically immutable.

Recommended Posts

Java and Swift comparison (1) Source control / Scope / Variables
[Java / Swift] Comparison of Java Interface and Swift Protocol
[Java] String comparison and && and ||
Java and Swift comparison (2) Basic type / arithmetic expression / control syntax / function definition
[Swift] Constants and variables
Java and Swift comparison (3) Class implementation / Class inheritance / Class design
[Java] Variables and types
Java programming (variables and data)
☾ Java / Iterative statement and iterative control statement
Same judgment / equal value judgment / comparison / order in Swift and Java
Java Primer Series (Variables and Types)
[Basic knowledge of Java] Scope of variables
Java starting from beginner, variables and types
[Java] Differences between instance variables and class variables
A Java engineer compared Swift, Kotlin, and Java.
[Java] Collection and StringBuilder operation method comparison
Java programming (static clauses and "class variables")
Comparison of Alibaba's open source Sentinel Java flow control project with Hystrix
[Swift vs Java] Let's understand static and final
Java control syntax
[Java] output, variables
Java control syntax
Java variable scope (scope)
[WIP] Java variables
Variables / scope (ruby)
[Java] Map comparison
Java framework comparison
Java variable scope
Java and JavaScript
XXE and Java
Java session scope
The comparison of enums is ==, and equals is good [Java]
[Java] Difference between static final and final in member variables
[Java] Refer to and set private variables with reflection
Java variable scope (range where variables can be seen)
[Introduction to Java] Variable scope (scope, local variables, instance variables, static variables)
Equivalence comparison of Java wrapper classes and primitive types
[Java Silver] What are class variables instance variables and local variables?