显示数据时出现整数数组错误

时间:2016-12-19 00:25:11

标签: arrays swift

我有一个包含偶数数组的attrribute evenNum,我喜欢将存储在属性中的数组打印到控制台 像这样

  

[" 2,6,8,10和#34; ," 24,22,20"," 2,6,34"]

所以我这样做并得到了错误,该错误显示在下面的评论中

 var evenNumArr:[Int] = []

let results = try context.fetch(request)

    if results.count > 0
    {
        for result in results as! [NSManagedObject]
        { 

  if let evenNumbers = result.value(forKey: "evenNum") as? [Int]
    {
        //Cannot convert value of type '[Int]' to excepted argument type 'int'
        evenNumArr.append(evenNumbers)
    }
    }
    print(evenNumArr)

我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

看起来你想要一个数组数组。您需要更改evenNumArr的声明方式:

var evenNumArr:[[Int]] = []

if let evenNumbers = result.value(forKey: "evenNum") as? [Int]
{
    evenNumArr.append(evenNumbers)
}

print(evenNumArr)

答案 1 :(得分:0)

它在错误中告诉你。您尝试将evenNumbers附加到[Int]中的let evenNumbers = result.value(forKey: "evenNum") as? [Int] 字段添加到:

evenNumArr

Int

组成的let ones = [Int]() var twos = [Int]() twos += ones 数组

您只能添加与数组包含的相同类型。

在Swift中你可以组合数组:

<Window
x:Class="Tabs.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Tabs"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="525"
Height="350"
mc:Ignorable="d">
<Grid>
    <TabControl
        Width="340"
        Height="202"
        Margin="21,41,0,0"
        HorizontalAlignment="Left"
        VerticalAlignment="Top"

        >
        <TabItem Header="Page 1">
            <Grid Background="#FFE5E5E5" DataContext="{Binding MainViewModel.FirstViewModel}">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="11*"/>
                    <ColumnDefinition Width="24*"/>
                    <ColumnDefinition Width="34*"/>
                    <ColumnDefinition Width="265*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Height="100" Text="{Binding MainViewModel.FirstViewModel.Text}" Grid.ColumnSpan="4" Margin="0,37" />
            </Grid>
        </TabItem>  
        <TabItem Header="Page 2">
            <Grid Background="#FFE5E5E5" DataContext="{Binding MainViewModel.SecondViewModel}">
                <TextBlock Height="100" Text="{Binding Text}" />
            </Grid>
        </TabItem>
        <TabItem Header="Page 3">
            <Grid Background="#FFE5E5E5" DataContext="{Binding MainViewModel.ThirdViewModel}">
                <TextBox Height="100" Text="{Binding Input}" />
            </Grid>
        </TabItem>
    </TabControl>

</Grid>