Swift Cannot assign value of type 'String.SubSequence' (aka 'Substring') to type 'String'

substring がdeprecateになったために発生したerror

swift4より

f:id:happy_teeth_ago:20201023190135p:plain

  if let jokyo = mstJokyo {
        let header:String
        if (jokyo.content?.count ?? 0) == 0 {
            header = ""
        } else {
            // ascii:1,全角:2 count とし最大20count(全角10文字)の先頭文字
            // を状況文字列に使う
            var len:Int = 0
            let index = jokyo.content!.index(where: {
                len += ($0 <= "~" ? 1 : 2)
                return len > 20
            })

  if index == nil{
                header = jokyo.content!
            }else{

//ここでエラー
//以前はここでsubstringを利用
                header = jokyo.content![..<index!]
            }

SubSequenceとはつづいて起こること 連続していること つまり、連続して起こることをString型に詰め込めないと行っている

ここは文字列をスライスしている

よって

String型にキャストしてあげたら良い

  if let jokyo = mstJokyo {

//ここ headerがString型 ポイント
        let header:String
        if (jokyo.content?.count ?? 0) == 0 {
            header = ""
        } else {
            // ascii:1,全角:2 count とし最大20count(全角10文字)の先頭文字
            // を状況文字列に使う
            var len:Int = 0
            let index = jokyo.content!.index(where: {
                len += ($0 <= "~" ? 1 : 2)
                return len > 20
            })

 if index == nil{
                header = jokyo.content!
            }else{
                header = String(jokyo.content![..<index!])
            }