Swift ジェネリクス型で switch判定

Pocket

Swiftジェネリクス型という言い方が正しいのか? とも思ったが

公式に Genericsと書いていたので 従うことにします。

下↓のコード の引数obj :Tの型でswitchする コード例です。

struct A: Codable{ var a: String}
struct B: Codable{ var b: String}

func test<T>(_ obj: T) -> String{
	switch type(of:obj) {
	case is String.Type:
		return obj as! String
	case is Int.Type:
		return String( obj as! Int )
	case is A.Type:
		let anser:String = (obj as! A).a
		return anser
	case is B.Type:
		let anser:String = (obj as! B).b
		return anser
	default:
		return ""
	}
}
    
var resultStr = ""
resultStr = test(Int(123))
resultStr = test("abc")
resultStr = test(A(a: "Codable A"))
resultStr = test(B(b: "Codable B"))
print(resultStr)

test<T>()というファンクションで 引数obj が Stringか Intもしくは struct AかBかをswitch判定しています。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA


2022 MJELD TECHNOLOGIES. ALL RIGHTS RESERVED