0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Swift】入力された郵便番号と都道府県が正しい情報か確認する

Last updated at Posted at 2021-10-19

iOSアプリなどで住所を入力してもらう際に、郵便番号と都道府県が一致しているか確認する際のコード。

コードはあまり美しくありませんがご了承ください。

CLGeocoderを使って郵便番号から都道府県を出力させ、入力値との相違を確かめるのですが、CLGeocoderから出力される都道府県名はローマ字。

そこでCLGeocoderで出力されるローマ字とユーザーが入力する日本語の都道府県名を一致させるための辞書を作る。

let RomeKanjiPrefecture = ["北海道": "Hokkaido","青森県": "Aomori","岩手県": "Iwate","宮城県": "Miyagi",
"秋田県": "Akita","山形県": "Yamagata","福島県": "Fukushima","茨城県": "Ibaraki",
"栃木県": "Tochigi","群馬県": "Gunma","埼玉県": "Saitama","千葉県": "Chiba",
"東京都": "Tokyo","神奈川県": "Kanagawa","新潟県": "Niigata","富山県": "Toyama",
"石川県": "Ishikawa","福井県": "Fukui","山梨県": "Yamanashi","長野県": "Nagano",
"岐阜県": "Gifu","静岡県": "Shizuoka","愛知県": "Aichi","三重県": "Mie",
"滋賀県": "Shiga","京都府": "Kyoto","大阪府": "Osaka","兵庫県": "Hyogo",
"奈良県": "Nara","和歌山県": "Wakayama","鳥取県": "Tottori","島根県": "Shimane",
"岡山県": "Okayama","広島県": "Hiroshima","山口県": "Yamaguchi","徳島県": "Tokushima",
"香川県": "Kagawa","愛媛県": "Ehime","高知県": "Kochi","福岡県": "Fukuoka",
"佐賀県": "Saga","長崎県": "Nagasaki","熊本県": "Kumamoto","大分県": "Oita",
"宮崎県": "Miyazaki","鹿児島県": "Kagoshima","沖縄県": "Okinawa"]

あとはユーザーの入力した都道府県名と郵便番号をもってくるだけ。


//都道府県を格納しておく変数
var prefecture : String = "東京都"


//郵便番号のバリデーション
CLGeocoder().geocodeAddressString("0000000", completionHandler: {(placemarks, error) -> Void in
    //存在しない郵便番号
    if((error) != nil){
        print("郵便番号が存在しない")
    }
    if let placemark = placemarks?.first {
        //郵便番号と県名が異なる(日本語とローマ字)
        if placemark.administrativeArea != self.prefecture && 
placemark.administrativeArea != self.RomeKanjiPrefecture[self.prefecture] {
            print("郵便番号と都道府県が違います")
        }
        else{
            print("成功")
        }
    }
})

Swiftのお役立ち情報

0
2
0

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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?