0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

タプルをcontains対応させる一工夫【swift】

Posted at

腐ってやがる...まだ、早すぎたんだ!

はじめに

  • またです。また、swiftのタプルのクソ仕様に苦しめられたので、対応します。
  • 今回のお題はこれ、配列のメソッドcontainsです。
let nums = [1,2,3,4]
print(nums.contains(1)) // true

今回の問題

  • containsをタプルに使ってみたら、エラー発生です。
let tpls = [(1,2),(3,4)]
print(tpls.contains((1,2)))
- error: missing argument label 'where:' in call
- error: cannot convert value of type '(Int, Int)' to expected argument type '((Int, Int)) throws -> Bool'
  • swiftのタプルは腐ってやがるなぁ...森にお帰りくださいと言いたくなるけど、そういうワケにもいかないので、誰か同じ被害に遭ってないかな?と思ったら、qiitaに先人がいらっしゃいました。助かった!

  • ...9年前から、swiftは進化してないのか...それとも、タプルはswiftで使っちゃ駄目なの?

swiftで苦労している君に紹介するコード

  • 先人の知恵を借りて解決したから、「捧げる」じゃなくて、「紹介する」にしました。
  • はいこれ
extension Sequence {
    func contains<T:Equatable,U:Equatable>(_ element: (T, U)) -> Bool {
        return (self as! [(T, U)]).contains { $0 == element }
    }
}

let tpls = [(1,2),(3,4)]
print(tpls.contains((1,2))) // true
print(tpls.contains((2,3))) // false

さいごに

  • ここまで、swiftでタプルが冷遇されているのをみると、使ったら問題でも起きちゃうのかな?と不安になるね。ドキがムネムネしちゃいます。
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?