小程序遍历数据swift
2017-10-22 19:04:16 J_mine 阅读数 1039

(1) 编写一个程序,能交换两个变量的数值
例如: 变量a值为20,变量b值为30,调用函数后,a的值变为30,b 的值变为20

答案:   -func swap(a: inout Int , b:inout Int){
            let temp = a
             a = b
            b = temp
        }
        var x = 20 , y = 30
        swap(a:&x , b:&y)
        print(x,y)

(2) 编写一个程序,求1! + 2! + 3! + 4!的和
要求:使用嵌套定义函数实现

答案: func getSum(number: Int) -> Int {
    //求某个数阶乘的结果
    func getFactorIal(num: Int) -> Int {
        var sum = 1
        for _ in 1...num {
            sum += 1
        }
        return sum
    }
    var total = 0
    for item in 1...number {
        total += getFactorIal(num: item)
    }
    return total
}
print(getSum(number: 3))

(3) 古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

答案:func getFinboNum(num: Int) ->Int{
            if num == 1 || num == 2 {
             return 1
            }
        return (getFinboNum(num: num - 1) + getFinboNum(num: num - 2))
}
for month in 1...10{
    print("\(month):\(getFinboNum(num: month))")
}

(4) 打印出所有的“水仙花数”,所谓“水仙花数”是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个“水仙花数”,因为153=1的三次方+5的三次方+3的三次方

答案 :for number in 100...999{
    var hunder = number / 100
    var ten = number / 10 % 10
    var num = number % 10
   let sum = pow(Decimal(hunder), 3) + pow(Decimal(ten), 3) +  pow(Decimal(num), 3)
    if sum == Decimal(number){
        print(number)
    }
}   

(5) 编写一个程序,要求可以把一个字符串中的每一个字符,如果是大
写字母变小写字母,如果是小写字母变大写,如果是其他字符不变
例如: 字符串China23beiJing 经过程序转换为cHINA23BEIjING

答案:
/*
 函数,将大写字母变小写,小写字母变大写,其他不变
 */
func changeCharcter (chNum:Character) -> Character {
    //将字符转成整数

    var chStr = String(chNum)   //将字符转成字符串
    var num:UInt32 = 0  //用于接受字符整数值的变量
    for item in chStr.unicodeScalars {
        num = item.value    //循环只执行一次,获取字符的整数的值

    }
    /*
     如果是大小写字母,转换数值
     */
    //如果是大写字母
    if num >= 65 && num <= 90 {
        num += 32
    }
        //如果是小写字母
    else if num >= 97 && num <= 122 {
        num -= 32
    }
    /*
     将整数转换为字符
     */
    let newChNum = Character(UnicodeScalar(num)!)
    return newChNum

}
var str = "China23beiJing "
var i = 0   //表示偏移量(循环变量初始值)
while i < str.characters.count {    //循环条件,包含循环变量的终止值
    var str1 = str[str.index(str.startIndex, offsetBy: i)]
//    str1 = changeCharcter(chNum: str1)

    str.replaceSubrange(str.index(str.startIndex, offsetBy:
        i)...str.index(str.startIndex, offsetBy: i),
                           with: String(changeCharcter(chNum: str1)))
    i+=1;   //循环变量值变化
}
print(str)

(6) 编写一个程序,要求接收一个数字,程序会将这个数字以二进制方
式打印,例如:数字10 , 以1010的方式打印出来

答案 :
    func binaryPrintIntNumber(num : Int) {

    var remainderArr:[Int] = []  //int数组,存储余数
    var quotient:Int = num  //表示商的变量,初始值是num
    while quotient > 0 {   //商的值是0
        let remainderNum = quotient % 2 //获取余数的值
        remainderArr.insert(remainderNum, at: 0)    //插入数组
        quotient /= 2   //商变换
    }
    for item in remainderArr {
        print(item, terminator: "")
    }
    print("")
}

var a = 10
binaryPrintIntNumber(num: a)
print(a)

(7) 编写一个程序,判断101-200之间有多少个素数,并输出所有素数

答案:
    var isPreimNum = true   //判断是否是素数,是就是true不是就是false
var sum = 0
for item in 101...200 {     //遍历101到200中的任意数
    for j in 2..<item {     //判断item是不是素数
        if item % j == 0 {
            isPreimNum = false
            break
        }
    }
    if isPreimNum {     //如果是素数
        print(item)     //打印这个素数
        sum += 1
    }
    isPreimNum = true

}
print(sum)}

(8) 编写一个程序,查看1、2、3、4四个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?

var sum1 = 0  //定义变量用于记录个数

for hudder in 1...4 {   //百位
    for ten in 1...4 {  //十位
        for num in 1...4 {  //个位
            if hudder != ten && hudder != num && ten != num {
                print(hudder*100 + ten*10 + num)
                sum1 += 1   //计算个数
            }
        }
    }
}

print(sum1)
2016-07-20 20:16:00 weixin_33859504 阅读数 74

纯代码版

没有多少注释,请谅解
//第一次修改:"+/-"按键在某种情况下无效BUG


2446853-199bc77d1272fbd9.png
UI图
//
//  ViewController.swift
//  uiTest
//
//  Created by Input on 16/7/20.
//  Copyright © 2016年 Input. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    let outputLabel = UILabel()
    let dicIntStr  = [ 11: "AC",  12: "DEL", 13: "%",   14: "/",
                       21: "7",   22: "8",   23: "9",   24: "*",
                       31: "4",   32: "5",   33: "6",   34: "-",
                       41: "1",   42: "2",   43: "3",   44: "+",
                       51: "0",   52: ".",   53: "+/-", 54: "=" ]
    
    var strOne = "0", strTwo = "", ch = "=";
    //接受运算符事件函数
    func testOperation (operation str : String) -> Void {
        var sum :Double = 0.0
        if strTwo.isEmpty {
            strTwo = strOne;
        }
        else if ch != "=" && !strOne.isEmpty {
            switch ch {
            case "+":
                sum = (Double)(strTwo)! + (Double)(strOne)!
            case "-":
                sum = (Double)(strTwo)! - (Double)(strOne)!
            case "*":
                sum = (Double)(strTwo)! * (Double)(strOne)!
            case "/":
                sum = (Double)(strTwo)! / (Double)(strOne)!
            default:
                break
            }
            strTwo = (String)(sum)
        }
        if strTwo == "0.0" { strTwo = "0" }
        ch = str; outputLabel.text = strTwo; strOne = "0";
    }
    //数字接受事件函数
    func inputNumber (numberCharcter number : String ) -> Void {
        if ch == "=" {
            strTwo = ""
        }
        if !strOne.isEmpty{
            if strOne[strOne.characters.startIndex] == "0" && !strOne.containsString(".") {
                strOne = ""
            }
        }
        strOne += number; outputLabel.text = strOne;
    }
    func idDButton() {
        if ch == "=" {
            strTwo = ""
        }
        let count = strOne.containsString(".")
        if !count {
            if strOne.isEmpty{
                strOne += "0."
            }
            else{
                strOne += "."
            }
        }
        outputLabel.text = strOne
    }
    
    func id0Button() {
        if ch == "=" {
            strTwo = ""
        }
        if !strOne.isEmpty {
            if strOne[strOne.characters.startIndex] == "0" {
                if strOne.containsString(".") {
                    strOne += "0"
                }
            }
            else {
                strOne += "0"
            }
        }
        else {
            strOne += "0"
        }
        outputLabel.text = strOne;
    }
    
    //清除缓存,重新开始计算
    func idACButton() {
        strOne = "0"; strTwo = ""; ch = "="
        
        outputLabel.text = strOne;
    }
    //取反
    func idXFButton() {
        if !strTwo.isEmpty && ch == "="{
            if strTwo != "0" {
                if strTwo[strTwo.characters.startIndex] == "-"{
                    strTwo.removeAtIndex(strTwo.characters.startIndex)
                }
                else {
                    strTwo.insert("-", atIndex: strTwo.characters.startIndex)
                }
                outputLabel.text = strTwo
            }
        }
        else{
            if !strOne.isEmpty && (strOne != "0" && strOne != "0."){
                if strOne[strOne.characters.startIndex] == "-"{
                    strOne.removeAtIndex(strOne.characters.startIndex)
                }
                else {
                    strOne.insert("-", atIndex: strOne.characters.startIndex)
                }
                outputLabel.text = strOne
            }
        }
    }
    //取百分数
    func idQYButton() {
        //调用计算函数:
        if strTwo.isEmpty{
            strTwo = strOne
        }
        else{
            testOperation(operation: "=")
        }
        ch = "/"; strOne = "100"
        testOperation(operation: "=")
    }
    //Del事件
    func idDelButton(){
        if !strOne.isEmpty && strOne != "0" {
            strOne = strOne.substringToIndex(strOne.endIndex.predecessor())
            if strOne.isEmpty { strOne = "0" }
        }
        if strOne == "-" {strOne = "0"}
        outputLabel.text = strOne
    }
    func funtest(tag :UIButton) {
        let T = (Int)(tag.tag)
        
        switch T {
        case 21, 22, 23, 31, 32, 33, 41, 42, 43:
            inputNumber(numberCharcter: "\((4 - T/10 )*3 + T%10)")
        case 14, 24, 34, 44, 54:
            testOperation(operation: dicIntStr[T]!)
        case 51:
            id0Button()
        case 52:
            idDButton()
        case 11:
            idACButton()
        case 13:
            idQYButton()
        case 53:
            idXFButton()
        case 12:
            idDelButton()
        default:
            break
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad(); view.backgroundColor = UIColor.init(red: 0.8, green: 0.7, blue: 0.6, alpha: 1)
        
        let wiDth = UIScreen.mainScreen().bounds.width,heiGht = UIScreen.mainScreen().bounds.height
        let butWidth = (wiDth - 9)/4, butHeight = 0.65*heiGht/5 - 3
        
        let tile = UILabel()
        
        tile.text = "简单计算器"; tile.frame = CGRectMake(0, 20, wiDth, 0.07*heiGht)
        tile.textAlignment = .Center;tile.backgroundColor = UIColor.init(red: 0.9, green: 0.5, blue: 0.3, alpha: 1)
        self.view.addSubview(tile)
        
        outputLabel.font = UIFont.systemFontOfSize(72)
        outputLabel.textAlignment = .Right;
        outputLabel.backgroundColor = UIColor.greenColor()
        outputLabel.adjustsFontSizeToFitWidth = true;
        outputLabel.text = "0"
        outputLabel.frame = CGRectMake(0, 0.1*heiGht, wiDth, 0.25*heiGht)
        self.view.addSubview(outputLabel)
        
        for i in 1 ..< 6 {
            for j in 1 ..< 5 {
                let button = UIButton()
                
                button.frame = CGRectMake((CGFloat)(j - 1)*(butWidth + 3), 0.35*heiGht + ((CGFloat)(i) - 1)*(butHeight + 3) + 3, butWidth, butHeight)
                button.tag = i*10 + j; button.setTitle(dicIntStr[button.tag], forState: .Normal)
                button.setTitleColor(UIColor.blackColor(), forState: .Highlighted)
                button.backgroundColor = UIColor.redColor()
                button.addTarget(self, action: #selector(funtest), forControlEvents: .TouchUpInside)
                
                self.view.addSubview(button)
            }
        }
    }    
}
2015-11-09 20:52:00 qq_32774515 阅读数 35

swift 遍历

 

 

最简单的一个遍历数组

for 随便起个名字 in

升级

上面的看不懂的话,这个应该会简单点

 

 

import UIKit
let interestingNumbers = [
    "prime": [2,3,5,6,11,13],
    "prime1": [1,1,2,3,5,8],
    "prime2": [1,4,9,16,25],
]
var largest = 0
for (kind,numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
print(largest)

//////////////////////////
let hehe = [1:[22,33],2:[12,32]]
var xx = 0
for (name,array) in hehe {
    for number in array {
        print(number)
    }
}
////////////////////////

var intArray = [1,23,4,5]
for int in intArray {
    print(int)
}

 

posted on 2015-11-09 20:52 Zing_Z 阅读(...) 评论(...) 编辑 收藏

2015-11-09 20:52:00 weixin_30260399 阅读数 3

 

 

最简单的一个遍历数组

for 随便起个名字 in

升级

上面的看不懂的话,这个应该会简单点

 

 

import UIKit
let interestingNumbers = [
    "prime": [2,3,5,6,11,13],
    "prime1": [1,1,2,3,5,8],
    "prime2": [1,4,9,16,25],
]
var largest = 0
for (kind,numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
print(largest)

//////////////////////////
let hehe = [1:[22,33],2:[12,32]]
var xx = 0
for (name,array) in hehe {
    for number in array {
        print(number)
    }
}
////////////////////////

var intArray = [1,23,4,5]
for int in intArray {
    print(int)
}

 

转载于:https://www.cnblogs.com/zdfbk/p/4951089.html

2016-04-25 01:14:00 weixin_30258027 阅读数 1

 

// see at http://swifter.tips/enum-enumerate/


// 貌似有些空格在粘贴的时候没有了...    = =!


import Foundation

 

enum Suit: String {

    case Spades = "黑桃"

    case Hearts = "红桃"

    case Clubs = "草花"

    case Diamonds = "方片"

}

 

enum Rank: Int, CustomStringConvertible{

    case Ace = 1

    case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten

    case Jack, Queen, King

    var description: String {

        switchself {

        case .Ace:

            return"A"

        case .Jack:

            return"J"

        case .Queen:

            return"Q"

        case .King:

            return"K"

        default:

            returnString(self.rawValue)

        }

    }

}

 

protocol EnumeratableEnumType {

    staticvar allValues: [Self] {get}

}

 

extension Suit: EnumeratableEnumType {

    static var allValues: [Suit] {

        return [.Spades, .Hearts, .Clubs, .Diamonds]

    }

}

 

extensionRank: EnumeratableEnumType {

    static var allValues: [Rank] {

        return [.Ace, .Two, .Three,

                .Four, .Five, .Six,

                .Seven, .Eight, .Nine,

                .Ten, .Jack, .Queen, .King]

    }

}

 

for suit in Suit.allValues {

    for rank in Rank.allValues {

        print("\(suit.rawValue)\(rank)")

    }

}


转载于:https://www.cnblogs.com/xilifeng/p/5429108.html

swift 遍历枚举

阅读数 57

Swift数组的遍历

阅读数 53

Swift字符串遍历

阅读数 29

swift -数组的遍历

阅读数 82

Swift - 字典遍历

阅读数 48

字典遍历

博文 来自: weixin_33845477
没有更多推荐了,返回首页