Swift代码在Xcode控制台无输出,如何查看运行结果?
解决Xcode中看不到代码输出的问题
你的代码只定义了numerator()函数但没有调用它,所以内部的逻辑根本没执行,自然看不到print的输出内容。
快速解决方法
在函数定义的外部添加调用语句,触发代码执行:
func numerator() { let nums = [2,7,11,15] let target = 26 for i in nums{ for (index, j) in nums.enumerated() { if i+j == target { print(index) } } } } numerator() // 调用函数,执行内部逻辑
额外优化建议
当前代码会重复输出相同的匹配结果(比如11+15和15+11都会触发输出),可以优化为只查找不重复的索引对:
func numerator() { let nums = [2,7,11,15] let target = 26 for (iIndex, i) in nums.enumerated() { // 从当前元素的下一位开始遍历,避免重复匹配 for jIndex in iIndex+1..<nums.count { let j = nums[jIndex] if i + j == target { print("匹配的索引组合:\(iIndex) 和 \(jIndex)") } } } } numerator()
内容的提问来源于stack exchange,提问作者user20166709
相关产品推荐
相关产品推荐

