Dart언어 Swift, C와 비교하며.

로건·2022년 6월 27일
1

Dart

목록 보기
1/3

C와 Swift 언어에 비교하며 Dart의 차이점 정리

선언 문법

  • 변수선언 - 선언 방법
    • var
      초기화한 값의 타입으로 지정됨.
      But, 특이한건 선언 후 대입할때는 타입을 계속 바꿔도 문제 없음
      ```dart
      var name = "string";
      name = 1; // Error
      
      var hello;
      hello = "string";
      hello = 1; // 가능
      ```
    • String, int, double
      변수선언 시 타입을 지정하면서 선언
      ```dart
      String name = "string";
      ```
    • dynamic
      타입을 계속 바꿀 수 있음
      ```dart
      dynamic name = "string";
      name = 1;
      ```
  • 변수선언 - nullable & non-nullable Swift의 Optional과 비슷한 느낌.(But, Optional Binding은 없어도 됨)
    변수선언시 ?를 같이 붙여주면 nullable → null값이 들어갈 수 있다는 뜻
    사용시 !를 붙이면 절대 null이 아니라는 뜻
    String? name = "string";
    name = null;
  • 변수선언 - final과 const 공통점
    • final과 const 키워드가 붙은 변수는 초기화 이후 수정 불가

    • final과 const를 붙이면 var 키워드 생략 가능

      차이점

    • final은 빌드타임에 값을 가지고 있지 않아도 됨

    • const는 빌드타임에 값을 가지고 있어야 함.(즉 런타임에 동적할당되는 것들은 사용못한다는 뜻? 객체 등)

      final String finalName;
      name = "finalName";
      name = "finalName2";  // Error
      
      const String constName; // Error(빌드시에 값을 안가지고 있으므로)
      name = "constName";
  • Operator(연산, 비교, 타입비교, 논리)
    • 연산은 C와 거의 동일 But, nullable인 변수에 대입 시
      double? value = 1.0;
      // value가 null이면 3.0을 대입
      value ??= 3.0;
    • 타입확인
      String name = "string";
      number is String; // 타입이 맞는지?
      number is! String; // 타입이 다른지?
    • 논리 연산(&&, ||) 기능은 같음
  • List, Map, Set
    List<int> list = [1, 2, 3];
    list.length;
    list.add(3); // 끝에 추가
    list.remove(3); // index가 가장 낮은 1개만 지워짐
    
    Map<String, String> dict = {
      '1' : 'one',
      '2' : 'two',
      '3' : 'three'
    };
    dict.remove('5');
    dict.remove('3'); // 이렇게 삭제해야함
    
    Set<String> s = {
      'one', 'two', 'three'
    };
      
     s.contains('one');
    // 대부분의 기능이 Swift Array, Dictionary, Set와 같음.
  • 조건, 반복문
    • switch문에 각 case마다 break 넣어주기
    • for문은 C와 같음 & in 구문 사용가능
    • while, do while 문도 C와 같음
  • enum Swift와 같이 열거형 but 선언이 다름
    enum Status {
      approve,
      pending,
      reject
    }
    Status status = Status.pending
  • 함수 - 파라미터 기본적인 함수형태는 C와 동일
    • positional parameter
      순서대로 이름 작성 가능
    • optional parameter
      있어도 되고 없어도 되는 파라미터 - [ ]안에 작성
      ```dart
      void main() {
        test(1,2);
      }
      
      void test(int x, [int y = 10, int z = 20]) {
        print(x);
        print(y);
        print(z);
      }
      ```
    • named parameter
      이름이 있는 파라미터 (순서가 중요하지 않다)
      물론 여기 내에서도 positional parameteroptional parameter를 사용가능
      ```dart
      void main() {
        test(0, x: 1, y: 2, z: 3);
      }
      
      void test(int k, {
        required int x,
        required int y,
        int z = 3 // optional parameter
      }) {
        print(x);
        print(y);
        print(z);
      }
      ```
  • 함수 - Arrow Function 코드가 1줄일때 (Single line expression)
    void main() {
      print(test(0, x: 1, y: 2, z: 3));
    }
    
    int test(int k, {
      required int x,
      required int y,
      int z = 3 // optional parameter
    }) => k + x + y + z;
  • 함수 - typedef, 익명함수
    • typedef
      는 별명을 지정하는 키워드이다.
      자료형에도 사용가능하며
      함수에 사용시 명확한 함수의 타입이라고 할 수 있다.
      이렇게 타입 선언하고 함수에 파라미터로 넘겨줄 수도 있다.
      ```dart
      typedef GlobalFunc = int Function(int x, int y);
      
      void main() {
        GlobalFunc g = test1;
        g = test2;
        g = test3;
      
      	print(confirm(1,2,g));
      }
      
      int test1(int x, int y) => x + y;
      int test2(int x, int y) => x - y;
      int test3(int x, int y) => x * y;
      
      int confirm(int x, int y, GlobalFunc f) => f(x,y);
      ```
    • 익명함수
      함수에 이름이 없는 것. 변수에 담을 수 있다.
      var, dynamic, Function 키워드를 단 변수에 넣을 수 있음.
      ```dart
      void main() {
        var a = (){
          print("a");
        };
        
        
        Function b = (){
          print("b");
        };
        
        dynamic c = () {
          print("c");
        };
      }
      
      ```


Class

  • class 모든 class는 Object를 extends하고 있음.
  • class - 생성자
    • 생성자 - constructor
      class Idol {
        String name;
        List<String> l;
        
        Idol(String name, List<String> l)
          : this.name = name,
            this.l = l;
      	// or
      	Idol(this.name, this.l);
      }
    • 생성자 - named constructor
      이름이 있는 생성자를 만드는 것
      ```dart
      void main() {
        Idol.fromList(['g','h']);
      }
      
      class Idol {
        String name;
        List<String> l;
        
        Idol(this.name, this.l);
        
      	// fromList라는 이름의 생성자
        Idol.fromList(List<String> members)
          : this.name = members[0],
            this.l = members;
      }
      ```
  • class - 생성자에 const, final const는 성능상의 장점을 가져옴 생성자 앞에 const를 붙일 수 있음.
    그럴 경우멤버 프로퍼티는 모두 final이어야함
    void main() {
    	const  Idol("test", ["test"]);
      
    }
    
    class Idol {
      final String name;
      final List<String> l;
      
      const Idol(this.name, this.l);
      
      Idol.fromList(List<String> members)
        : this.name = members[0],
          this.l = members;
    }
    생성자 앞에 const를 붙이고 멤버를 같게 만든 두 객체는 같은 객체로 판단됨
  • class - file private 기능 클래스 이름 앞에 _를 붙이면 file내에서만 사용가능 외부에서는 사용불가능
  • class - 상속 extends로 부모 class 설정
    자식 init내 super 추가 모든 프로퍼티 중 마지막에 작성
    void main() {
      Idol(name: "아이돌1", cnt: 5);
      BoyGroup("아이돌2", 10, "hi");
    }
    
    class Idol {
      String name;
      int cnt;
      
      Idol({
        required this.name,
        required this.cnt
      });
      
      void printIdol() {
        print("idol");
      }
    } 
    
    class BoyGroup extends Idol{
      String greeting;
      
      BoyGroup(
        String name,
        int cnt,
        String greeting
      ): 
        this.greeting = greeting,
        super(
          name: name,
          cnt: cnt
        );
    }
    • Override 메서드 위 ‘@override’ 붙이기
  • interface 스위프트의 protocol.
    특이한 점은 interface도 class로 선언한다는 것
    채택하는 class에서 implements로 받으면 interface
    interface class를 직접 생성못하게 하는 키워드는 abstract
    void main() {
      BoyGroup("아이돌2");
    }
    
    abstract class IdolInterface {
      String name;
      IdolInterface(this.name);
      
      void sayGreeting();
    }
    
    class BoyGroup implements IdolInterface{
      String name;
      
      BoyGroup(this.name);
      
      void sayGreeting() {
        
      }
    }
  • generic 타입에 의존하지 않는 범용적인 코드 작성 시 사용
    재사용 및 깔끔한 표현이 가능
    void main() {
      
      Lecture<String, String> lecture = Lecture("id", "math");
    }
    
    class Lecture<T, X> {
      final T id;
      final X name;
      
      Lecture(this.id, this.name);
    }
  • 함수형
    map 함수의 결과는 iterable이므로 toList 해줘야함.
    filter가 아닌 where함수
    reduce는 prev, next 파라미터를 받고, 첫 prev는 List의 첫번째 값, next는 List의 두번째 값. 만약 List 내 값이 1개라면 그 값만 나옴, 리턴 되는 값이 항상 List 내 값타입과 같아야함.
    fold<타입>(최초값, 함수)은 Swift의 reduce와 같음
    casacading operator … 리스트를를 펼치는 것(각괄호 없애서 표시)

Dart만의 장점

  • cascade
    동일한 객체에서 연속적인 작업을 할때 ..로 표시하여 사용한다.

    void main() {
      Student student = Student();
      student
        ..age = 13
        ..name = "name2"
        ..printName();
    }
    
    class Student {
      int age = 12;
      String name = "test";
      List<String> friends = ["test2", "test3"];
    
      Student() { }
    
      void printName() {
        print(name);
      }
    }
profile
Life Designer

0개의 댓글