You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift出现"Cannot convert value of type"报错 求代码修复方案

Swift类型转换报错排查修复

所有报错均为语法、类型不匹配、基础API用法错误导致,核心问题点如下:

  • 字典类型定义错误:声明c_res为[String: String]类型,但实际需要存储字符对应的双计数值,类型完全不匹配,应使用键为Character、值为整数元组的字典类型。
  • 字符计数逻辑错误:使用Dictionary(uniqueKeysWithValues:)生成字符计数字典时,重复字符会触发运行时崩溃,该初始化方法要求所有键唯一,无法直接用于统计词频。
  • 字符串下标用法错误:Swift原生String不支持直接用整数下标取字符,必须先转为[Character]数组才能通过整数索引访问对应位置字符。
  • 运算符混淆:多处将相等判断==错写为赋值运算符=,触发语法/类型错误。
  • 字典遍历逻辑错误:Swift遍历字典得到的是(key, value)键值对元组,不能直接将遍历结果作为下标传入字典取值。
  • 可选值处理缺失:字典下标返回可选类型值,直接参与算术运算会触发类型错误,需要设置默认值或安全解包。

修复后可运行代码

import Foundation

// 读取输入并转为字符数组,支持整数下标访问
guard let inputT = readLine(), let inputS = readLine() else {
    fatalError("读取输入失败")
}
let t = Array(inputT)
let s = Array(inputS)
let sLen = s.count
let tLen = t.count

guard sLen <= tLen else {
    print(-1)
    exit(0)
}

// 统计模式串s的字符出现频次
var sCharCount: [Character: Int] = [:]
for c in s {
    sCharCount[c, default: 0] += 1
}

// 初始化滑动窗口的字符频次统计
var windowCharCount: [Character: Int] = [:]
for i in 0..<sLen {
    windowCharCount[t[i], default: 0] += 1
}

// 计算初始匹配度:窗口内字符计数和s的字符计数完全一致的字符种类数
var matchCount = 0
for (char, count) in sCharCount {
    if windowCharCount[char, default: 0] == count {
        matchCount += 1
    }
}

// 滑动窗口遍历所有可能的起始位置
for startIndex in 0...(tLen - sLen) {
    // 匹配度差1即符合"只差一个字符不同"的要求,输出位置
    if matchCount == sCharCount.count - 1 {
        print(startIndex)
        exit(0)
    }

    // 窗口右移,更新统计值
    guard startIndex + sLen < tLen else { break }
    // 移除窗口左边界移出的字符
    let leftOutChar = t[startIndex]
    if let targetCount = sCharCount[leftOutChar] {
        if windowCharCount[leftOutChar] == targetCount {
            matchCount -= 1
        }
        windowCharCount[leftOutChar, default: 0] -= 1
        if windowCharCount[leftOutChar] == targetCount {
            matchCount += 1
        }
    }
    // 加入窗口右边界新进入的字符
    let rightInChar = t[startIndex + sLen]
    if let targetCount = sCharCount[rightInChar] {
        if windowCharCount[rightInChar] == targetCount {
            matchCount -= 1
        }
        windowCharCount[rightInChar, default: 0] += 1
        if windowCharCount[rightInChar] == targetCount {
            matchCount += 1
        }
    }
}

// 无符合要求的位置
print(-1)

内容的提问来源于stack exchange,提问作者Artyom Osipov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 21:24:21