ã¯ããã«
ãååã¾ã§ã«Swiftã«ããiOSã¢ããªã®åºæ¬çãªéçºææ³ã«ã¤ãã¦èª¬æãã¾ãããé£è¼ç¬¬6åããã¯SwiftããObjective-Cãå¼ã³åºããObjective-Cã§ä½æãããã©ã¤ãã©ãªãå©ç¨ããæ¹æ³ã«ã¤ãã¦èª¬æãã¾ãã
ã対象èªè ãObjective-Cãåããæ¹ã¨ãã¦ããé¢ä¿ä¸ãObjective-Cèªä½ã®è¨èªä»æ§ãXcodeã®ä½¿ãæ¹ã«ã¤ãã¦ã¯è§£èª¬ãå²æããå ´åããããã¨ããäºæ¿ãã ãããåæ§ã«Swiftèªä½ã®èª¬æãå¿ ãããååã§ãªãå ´åãããã¾ãããã®ãããªå ´åã¯æ«å°¾ã®åèæç®çãåç §ãã¦ãã ããã
対象èªè
ãæ¬è¨äºã¯ã次ã®æ¹ã対象ã«ãã¦ãã¾ãã
- Objective-Cã®åºæ¬çãªããã°ã©ã ãåºæ¥ãæ¹
- Xcodeã使ããæ¹
Swiftããã®Objective-Cã®å©ç¨
ãSwiftã¯ãã¨ãã¨Objective-Cãå©ç¨ã§ããããã«è¨è¨ããã¦ãã¾ãããã®ãããããã¾ã§Objective-Cã§éçºããããã°ã©ã ããSwiftã§ä½æããå ´åã«ãå©ç¨ã§ãã¾ãããã¼ã¸ã§ã³ã¢ããã®ããã«Swiftã§ã¢ããªãä½ãç´ãå ´åã§ãããã¹ã¦ãSwiftã§æ¸ãç´ãå¿ è¦ã¯ããã¾ããã
Objective-Cã®ãã¡ã¤ã«ãé ç½®ãã
ãSwiftããObjective-Cã§ä½æããããã°ã©ã ãå©ç¨ããããã«ã¯ãããã¸ã§ã¯ãå ã«Objective-Cã®ã½ã¼ã¹ã³ã¼ããé ç½®ããå¿ è¦ãããã¾ããé ç½®ã®æ¹æ³ã«ã¯æ¬¡ã®2éããããã¾ãã
- 1ï¼ä»ã®ããã¸ã§ã¯ãã§ä½æããObjective-Cã®ãã¡ã¤ã«ãXcodeä¸ã§ãã©ãã°ï¼ãããããã
- 2ï¼ï¼»Fileï¼½âï¼»Newï¼½ããæ°è¦ã«Objective-Cã®ã¯ã©ã¹ãä½æãã
ã2ï¼ã®å ´åã¯ããã¡ã¤ã«ä½ææã«Languageã®é¸æãObjective-Cã«ãã¾ãã
Objective-Cã®ãã¡ã¤ã«ãSwiftããå¼ã³åºããããã«ãã
ãåé ã®ã©ã¡ãã®æ¹æ³ã§ããããã¸ã§ã¯ãå ã«Objective-Cã®ãã¡ã¤ã«ãé ç½®ããéã«ã¯ãXcodeãã次ã®ãããªã¢ã©ã¼ããåºã¾ãã
ããã®ã¢ã©ã¼ãã¯ãSwiftããObjective-Cãåç §ããããã«å¿ è¦ãªObjective-C Bridging Headerãã¡ã¤ã«ãä½æãããå¦ãã®ç¢ºèªã§ãããyesããé¸æããã¨èªåçã«[ããã¸ã§ã¯ãå]-Bridging-Header.hã¨ããååã®ãã¡ã¤ã«ãçæããã¾ããçæãããObjective-C Bridging Headerãã¡ã¤ã«å ã§ãå©ç¨ãããObjective-Cã®ããããã¡ã¤ã«ãã¤ã³ãã¼ããã¾ããé£è¼ç¬¬3åã§ä½æããObjective-Cã®Catã¯ã©ã¹ãå©ç¨ããå ´åã¯ã次ã®ããã«ããããã¡ã¤ã«ã®Cat.hãã¤ã³ãã¼ããã¾ãã
// // Use this file to import your target's public headers that you would like to expose to Swift. // #import "Cat.h"
ãObjective-C Bridging Headerãã¡ã¤ã«ã®ååã¯ãXcodeã®ã¢ããªã®è¨å®ã§ããBuild Settingå ã®é ç®ã«æ¬¡ã®ããã«å ¥ãã¾ãã
ãXcodeã®ã¢ã©ã¼ããããyesããé¸æãã¦ãã¡ã¤ã«ãä½æããå ´åã«ã¯ãèªåçã«ãã®é ç®ã«ãã¡ã¤ã«åãå ¥ãã¾ãããã以å¤ã«èªåã§Objective-C Bridging Headerãã¡ã¤ã«ãä½æããå ´åã«ã¯ãBuild Settingå ã®é ç®ã«ããã¡ã¤ã«åãè¨å ¥ãã¾ãã
SwiftããObjective-Cã®ã¯ã©ã¹ãå¼ã³åºã
ãåé ã¾ã§ã®è¨å®ãå®äºããã¨ãSwiftããObjective-Cã®ã¯ã©ã¹ãå¼ã³åºãã¾ããObjective-Cã®Catã¯ã©ã¹ãå¼ã³åºãä¾ã¯æ¬¡ã®ããã«ãªãã¾ãã
// Catã¯ã©ã¹ã®åæåå¦ç var cat = Cat(); // ããããã£ã«å¤ãæå® cat.name = "ãã" cat.age = 1
ãSwiftå ã§Objective-Cã®ã¯ã©ã¹ãå©ç¨ããéã«ããåæåå¦çã®å¾ã«ããããã£ã®æå®ãã¡ã½ããã®å®è¡ã¨ããé åºã¯å¤ããã¾ããããã é£è¼ç¬¬3åã§èª¬æããéããã¡ã½ããã®å¼ã³åºãæ¹ãåæåå¦çã®éã®initï½ã¡ã½ããã«é¢ãã¦ã¯ãSwiftå¼ã«è¨è¿°ãããã¨ã«ãªãã¾ãããã®ç¹ã«ããçæããã°ãObjective-Cã§ã®ã¢ããªéçºã¨åæ§ã«Objective-Cã®è³æºãå©ç¨ãããã¨ãã§ãã¾ãã次ç¯ããObjective-Cã®ã©ã¤ãã©ãªãç¨ãã¦å ·ä½çã«ãããã®äºæã«ã¤ãã¦èª¬æãã¾ãã