LoginSignup
23
18

More than 3 years have passed since last update.

Swift言語、C#言語とのコードを相互変換

Last updated at Posted at 2017-12-08

概要

Swift言語とC#言語でのコードの書き方の違いを比較してみました。
C#に慣れている人がSwiftで実装、
逆にSwiftに慣れている人がC#で実装する場合に参考として作成しました。

(前提条件)

  • 全ての機能は比較をしていません。(あくまで把握している部分のみ)
  • 2017/12月時点での比較内容です。

主に参考にしたサイト

検証環境

PC OS バージョン
Mac Sierra 10.12.6
開発環境 Swift C#
ツール xcode visual studio for mac
バージョン 7.3 9.2

言語

言語 使用バージョン
Swift 4.0.3
C# 7

変数

Swift

// 文字列型の変数「str」宣言
var str: String = "Hello, Swift"

C#

// 文字列型の変数「str」宣言
string str = "Hello, C#";

定数

Swift

let str: String = "Hello, Swift"

// 宣言のみも可能
let message: String
// 宣言だけした定数は一度のみ代入できる
message = "Message"
// 2度代入するとビルドエラーになる

C#

// ローカルスコープ内で定義した定数はconstを指定
const string str = "Hello, C#";

配列

Swift

var numbers: [Int] = [1, 2, 3]
var numbers = [1, 2, 3]

C#

int[] numbers = { 1, 2, 3 };
var numbers = new[] { 1, 2, 3 };

辞書

Swift

// 辞書データ作成を言語でサポートしている
var dictionary = ["one": 1, "two": 2]
for (key, value) in dictionary
{
  print( "key = \(key), value = \(value)" )
}

C#

using System;
// 辞書データを実装するためにはDictionaryクラスが必要
using System.Collections.Generic;

Dictionary<string, int> dic = new Dictionary<string, int>()
{
  {"one", 1},
  {"two", 2},
};

foreach (KeyValuePair<string, int> kvp in dic)
{
  Console.WriteLine($"key = {kvp.Key}, value = {kvp.Value}"); 
}

for文

Swift

for num in 0...3
{
    print(num)
}

var numbers = [4, 5, 6]
for num in numbers
{
    print( num )
}

C#

using System;

for (int i = 0; i < 4; ++i)
{
  Console.WriteLine(i);
}

var numbers = new[] { 4, 5, 6 };
foreach (int i in numbers)
{
  Console.WriteLine(i);
}

while文

Swift

var index = 0
while index < 5
{
    print(index)
    index = index + 1
}

C#

using System;

var index = 0;
while (index < 5)
{
  Console.WriteLine(index);
  index++;
}

if文

Swift

if index == 0
{
    print("index is \(index)")
}

C#

using System;

if ( index == 0 )
{
  Console.WriteLine("index is {0}", index);
} 

switch文

Swift

var number = 0
switch( number )
{
    case 0:
        print("0")
    case 1:
        print("1")
    default:
        print("error")
}

C#

using System;

var number = 0;
switch ( number )
{
  case 0:
    Console.WriteLine("0");
    break;
  case 1:
    Console.WriteLine("1");
    break;
  default:
    Console.WriteLine("2");
    break;
}

関数

Swift

// func 名前(引数)
func Func(num: Int)
{
}
Func(num: 1)
// 引数名を指定しないとエラーになる
//Func(1)

// _ 引数 とすると呼び出し時に引数名が不要になる
func Func2(_ num: Int)
{
}
Func2(1)

// func 関数名() -> 戻り値の型
func Func3() -> Int
{
    return 0
}

C#

class Funcsion
{
  public int num = 0;

  public void Func(int num)
  {
    this.num = num;
  }

  public int Func3()
  {
    return 0;
  }
}

Funcsion func = new Funcsion();
// 引数名を指定しての設定と指定なしの両方が可能
func.Func(num: 1);
func.Func(1);

int num = func.Func3();

構造体

Swift

struct Man
{
    var power = 10
    var name = ""

    init(name: String, power: Int)
    {
        self.name = name
        self.power = power
    }

    func walk()
    {
        print("\(self.name) walk \(self.power) power")
    }
}

C#

struct Man
{
  public int power;
  public string name;

  public Man(string name, int power)
  {
    this.name = name;
    this.power = power;
  }

  public void walk()
  {
    Console.WriteLine("{0} walk {1} power", this.name, this.power);
  }
}

クラス

Swift

class Woman
{
    fileprivate var power = 0
    fileprivate var name = ""

    init(name: String, power: Int)
    {
        self.name = name
        self.power = power
    }

    open func attack()
    {
       print("\(self.name) attack about \(self.power) power")
    }
}

C#

using System;

class Woman
{
  private int power;
  private string name;

  public Woman(string name, int power)
  {
    this.name = name;
    this.power = power;
  }

  public void attack()
  {
    Console.WriteLine("{0} attack about {1} power", this.name, this.power);
  }
}

インターフェイス

Swift

protocol Human
{
    func walk()
}

class Man: Human
{
    func walk()
    {
        print("man walk")
    }
}

class Woman: Human
{
    func walk()
    {
        print("woman walk")
    }
}

C#

using System;

interface Human
{
  void walk();
}

class Man : Human
{
  public void walk()
  {
    Console.WriteLine("man walk");
  }
}

class Woman : Human
{
  public void walk()
  {
    Console.WriteLine("woman walk");
  }
}

ジェネリクス

Swift

class Console
{
    open func PutMessage<T>(data: T)
    {
        print(data)
    }
}

var console = Console()
console.PutMessage(data: 3)

C#

class Console
{
  public void PutMessage<T>(T data)
  {
    System.Console.WriteLine(data);
  }
}

Console console = new Console();
console.PutMessage("");

例外処理

Swift

// 例外の種類を列挙
enum HumanErrorType: Error
{
    case Unknow(String)
}

class Human
{
    fileprivate var name = ""

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

    func putName() throws
    {
        guard self.name != "" else
        {
            throw HumanErrorType.Unknow("Human NonBlankName")
        }

        guard self.name.count > 1 else
        {
            throw HumanErrorType.Unknow("1LengthName or Less")
        }

        print(self.name)
    }
}

var bob = Human(name: "bob")
do
{
    defer
    {
        print("final")
    }
    try
        bob.putName()
}
catch HumanErrorType.Unknow(let message)
{
   print(message)
}

C#

using System;

class Human
{
  private string name = "";

  public Human(string name)
  {
    this.name = name;
  }

  public void PutName()
  {
    if (this.name == "")
    {
      throw new Exception("Human NonBlnakName");
    }
    else if ( this.name.Length <= 1 )
    {
      throw new Exception("1LengthName or Less");
    }

    Console.WriteLine( this.name );
  }
}

try
{
   Human bob = new Human("bob");
   bob.PutName();
}
catch (Exception e)
{
  Console.WriteLine(e.Message);
}
finally
{
  Console.WriteLine("finale");
}
23
18
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
18