Swift Array contains function makes build times long

前端 未结 1 882
旧巷少年郎
旧巷少年郎 2021-01-23 22:52

I\'m not sure if this belongs in Stack Overflow, if it doesn\'t please let me know.

I have this piece of code that adds contacts to an array, if a contact with that phon

相关标签:
1条回答
  • 2021-01-23 23:45

    Chained + is the most common cause of slow build times in my experience. When people complain about build times, I always ask "you've got chained +, don't you." Have been right about 90%. For example:

    let name: String = contact.givenName + " " + contact.middleName + " " + contact.familyName
    

    and also

    contacts.contains({($0.givenName + " " + $0.middleName + " " + $0.familyName) == name})
    

    Use interpolation rather than chained +:

    "\(contact.givenName) \(contact.middleName) \(contact.familyName)"
    

    Or join an array:

    [contact.givenName, contact.middleName, contact.familyName].joined(separator: " ")
    

    In this particular case, I'd almost certainly make a helper though:

    extension Contact {
        var fullName: String {
            return "\(contact.givenName) \(contact.middleName) \(contact.familyName)"
        }
    }
    

    Then much of the rest of your code would get simpler.

    The problem with chained + is that it has many overloads, and so the compiler has to do a combinatorially explosive search of all the different versions of + it might use here.

    0 讨论(0)
提交回复
热议问题