iOS_swift문법 정리

Swift[Generic] ... <T>

ios_DEV 2020. 7. 23. 09:59

스위프트에는 Generic 타입이 있다.

 

타입을 미리정의하지 않고 그때 그때 결정 할수있다.

 

예를 들면 데이터 콜백 모듈같은 경우 Class나 Struct에 담아 사용할때 

결과 형을 호출하는곳에서 정할수있다.

 

제너릭 타입에 <T>를 사용하여 정의한다!

   

 

func testGeneric<T>(type:T.Type , completion: @escaping (_ result: T?) -> Void)

{

        

}

 

 

type 에  어떤 타입으로 리턴받을지를 정하고

탈출 클로져로 해당 타입의 객체를 던져 주었다.

 

 

 

struct TestSt

{

    var test1 = 1

    var test2 = 2

    var test3 = ""

}

 

class TestClass2

{

    var test5 = 1

    var test6 = 2

    var test7 = ""

}

 

class ViewController: UIViewController

{

    

    override func viewDidLoad() {

        super.viewDidLoad()

 

        self.testGeneric(type: TestSt.self, completion: {(item) in

            item?.test1 /// TestSt클래스의 객체로 받겠다.

        })

        

        self.testGeneric(type: TestClass2.self, completion: {(item) in

            item?.     ///TestClass2클래스의 객체로 받겠다.

        })

    }

    

    func testGeneric<T>(type:T.Type , completion: @escaping (_ result: T?) -> Void)

    {

        

    }

    

.

.

.

 

 

 

통신 모듈에 적용한다고 가정하면!

Codable  프로토콜인 상태를 받아 JSON 데이터를 제네럴 겍체로 바꾸어 리턴 해주도록 한다!!!

 

    func testGeneric<T:Codable>(type:T.Type , completion: @escaping (_ result: T?) -> Void)

    {

        let json = """

        {"test1":123,"test2":567,"test3":"ttttt3"}

        """.data(using:.utf8)!

        ///API 리스폰스를 받았다고 가정.

        

        let decoder = JSONDecoder()

        do {

            let result = try decoder.decode(type, from: json)

            print("33333")

            completion(result)

        } catch {

            print(error.localizedDescription)

        }

    

        

    }